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);
}
You asked for a solution and an explanation.
The solution
Explanation
Your
doublefunction needs toreturnsomething in any case. Your function has these cases:if (x >= 50): you setresultto some value, but you do notreturnanythingelse if( x >= 40 ): you setresultto some value, but do notreturnanythingelse if( x >= 0 ): you setresultto some value, but do notreturnanythingelse: You do not initializeresult, but you return itLet's not forget that
else ifmeans that none of the conditions of theifand earlierelse ifs than the current condition was true, but the condition of the currentelse ifis true and let's not forget thatelsemeans that "none of the above is true". Since you had yourreturninside yourelse, in the first three cases you do notreturnanything, hence, you violate the best practices of the language. This is why, the solution is toreturnsomething, no matter what.