4
I have the following code that should receive 4 numbers and tell which one is the largest.
#include <stdio.h>
int max_of_four(int x, int z, int y, int w);
int main() {
int a, b, c, d;
scanf("%d %d %d %d", &a, &b, &c, &d);
int ans = max_of_four(a, b, c, d);
printf("%d", ans);
return 0;
}
int max_of_four(int x, int z, int y, int w){
int max1, max2;
x > z ? max1 = x : max1 == z;
y > w ? max2 = y : max2 == w;
return max1 > max2 ? max1: max2;
}
My doubt is in the function max_of_four
. I compare two numbers twice and the largest should be assigned to their respective variable. In the else
(... : max1 == z; / ... : max2 == w;)
instead of ==
should be =
, but if I put the =
the code gives the error:
lvalue required as left operand of assignment
On the other hand, if I leave the ==
the code does not run right, not printing the highest value if it is in second or fourth position.
I know I could do the following:
int max1 = x > z ? x : z;
int max2 = y > w ? y : w;
But I’d like to know if my code is incorrigible or if I’m missing something.
There is not much point in this == because the result will be true or false and not an assignment. The correct is what you put in the end.
– anonimo
Function was created after. I’ve had this problem. Always leave main on the last lines
– Maury Developer
Try: (x > z) ? (max1 = x) (max1 = z).
– anonimo
@Maurydeveloper The function is at the end, but I declared it at the top before the main function. The tip to put in parentheses the terms worked and Luiz Augusto explained well what happens. Thank you to all!
– user154007