'want t print the max integer ot of four but extra 1 is added to the result [closed]
#include <stdio.h>
int max_of_four(int, int, int, int);
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);
}
int max_of_four(int a, int b, int c, int d) {
if (a > b && a > c && a > d) {
return printf("%d", a);
}
if (b > a && b > c && b > d) {
return printf("%d", b);
}
if (c > a && c > b && c > d) {
return printf("%d", c);
}
if (d > a && d > b && d > c) {
return printf("%d", d);
}
return 0;
}
Solution 1:[1]
This happened because you returned and printed the value of printf(), which printed only 1 character. You need to return only the number not the result of printf().
Also, always check whether scanf() was successful or not.
Final Code
#include <stdio.h>
int max_of_four(int a, int b, int c, int d) {
if (a > b && a > c && a > d)
return a;
if (b > a && b > c && b > d)
return b;
if (c > a && c > b && c > d)
return c;
if (d > a && d > b && d > c)
return d;
return 0;
}
int main() {
int a, b, c, d;
if(scanf("%d %d %d %d", &a, &b, &c, &d) != 4)
{
fprintf(stderr, "bad input\n");
return 1;
}
printf("%d\n", max_of_four(a, b, c, d));
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Darth-CodeX |
