My subprogram does not work in C language

63 Views Asked by At

I wrote a subprogram in C with Xcode that calculates a partial function but it does not work.

I know there is a a lot wrong with " return " statements but i couldn't find a way to make it better.

I made "return (result * 1 )" and "return(result = result)" for return, took every function between return parentheses like " return(result = pow(x,5) + pow(y,3)); " but none of them worked.

Can you please show me how to make it right and explain why?

#include <stdio.h>
#include <math.h>

double
funmath(int x, int y)
{
    double result;
    
    if( x >= 50 )
        result = pow(x,5) + pow(y,3);
    else if( x >= 40 )
        result = 5 * x + y + 9;
    else if( x >= 0 )
        result = x / 5 + 7 * y;
    else
    
    return(result);
}

1

There are 1 best solutions below

3
Lajos Arpad On

You asked for a solution and an explanation.

The solution

#include <stdio.h>
#include <math.h>

double
funmath(int x, int y)
{
    double result = -42; //You can use some other default value instead if you prefer
    
    if( x >= 50 )
        result = pow(x,5) + pow(y,3);
    else if( x >= 40 )
        result = 5 * x + y + 9;
    else if( x >= 0 )
        result = x / 5 + 7 * y;
    
    return(result);
}

Explanation

Your double function needs to return something in any case. Your function has these cases:

  • if (x >= 50): you set result to some value, but you do not return anything
  • else if( x >= 40 ): you set result to some value, but do not return anything
  • else if( x >= 0 ): you set result to some value, but do not return anything
  • else: You do not initialize result, but you return it

Let's not forget that else if means that none of the conditions of the if and earlier else ifs than the current condition was true, but the condition of the current else if is true and let's not forget that else means that "none of the above is true". Since you had your return inside your else, in the first three cases you do not return anything, hence, you violate the best practices of the language. This is why, the solution is to return something, no matter what.