0
Why does my code below throws an error?
static int Max(int x,int y) { if(x>y) { return x;} else if(x<y) {return y;} else { Console.WriteLine("x is equal to y");} } static void Main (string[]args) { Max(2, 4); } //output = error , Program.Max(int, int): not all code paths return a value Why???
6 Respuestas
+ 4
If x equals y, you only print a message, but don't return a value, while the function expects you to return an integer value. If the return type of your function is not void, it must return a value, which might not be the case here, therefore an error is raised.
+ 4
Just add return in your else statement, like this:
...
else{
Console.WriteLine("x is equal to y");
return x;
}
...
+ 2
If you say static INT Max, that means function MUST return integer. Else clause doesn't return anything, you simply write to console, you must return some number just like in if and else if
+ 2
When you return value it's not printed, you must print it manually, like Console.writeLine(Max(2,3))... For else clause you can return anything of your own choice, but remember not to use = but == if you want to test equality
0
Shadow didnt get you still...can you point out directly where the error is or simply write the correct code
Thanks
0
Elva got it now... I should put //return x=y; not the Console.Write....... But am stuck a little bit ...because i used if statement when the first if is not true it gives no output to my code while there is more conditional down like else if and else
HOW TO SOLVE THIS PROBLEM...OR SIMPLY HOW TO GIVE THE MAXIMUM NUMBER IN MY CODE ABOVE