0
C programming
İnt compute(int a, int b, int c) {if (b = c+2*a) printf("%d", b/5); else if (a = b+c) printf("%d", a/3); else printf("0");} int main() { int x=10 ; compute (x-12, x-5, x-6); } Answer is 1 can you explain it why? I think that answer is 0.
1 ответ
0
Looking at your code in a bit more readable way:
#include <stdio.h>
int compute(int a, int b, int c) {
if (b = c + 2 * a){
printf("%d\n", b / 5);
} else if (a = b + c){
printf("%d\n", a / 3);
} else {
printf("0");
}
}
int main(void) {
int x = 10;
compute(x-12, x-5, x-6);
return 0;
}
Your compute would do the following:
first if(b = (4 + 2 * -2)) evaluates to b = 0 which in a true false test, 0 equates to false so your first printf is skipped.
b has been reassigned to 0 now
second if(a = 0 + 4) evaluates to a = 4 which any non-zero in a true false test evaluates to true so you printf now runs
printf("%d", 4/3) evaluates to 1 because 4 / 3 == 1 with 1 remainder but in integer math the remainder is dropped.
Thus you get the return of 1 not 0.
If you would have compiled this with -Wall you would have gotten some errors:
int compute not having a return value
in if statements using assignment instead of equals
not sure if that was part of the assignment to catch or not.