Reputation: 17
My function (max_of_four) needs the return;
code but by adding it, I also get a zero to my output which I don't want. I only want the content of int c (the number 6) to be printed.
Here is the code:
#include <stdio.h>
/*
Add `int max_of_four(int a, int b, int c, int d)` here.
*/
int max_of_four(int a, int b, int c, int d){
if ((c > a) && (c > b) && (c > d)) {
printf("%d", c);
}
return ;
}
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;
}
Please help me to get just the integer c (6) printed, without the zero (it looks like 60 now).
Upvotes: 0
Views: 106
Reputation: 33631
In max_of_four
, you have [only] return;
. You need a return
that returns a value
You probably don't want a printf
in the function (i.e.) it's a debug printf
.
If we believe the name of your function, the function has to compare all values for maximum.
Here's some refactored code:
#include <stdio.h>
/*
Add `int max_of_four(int a, int b, int c, int d)` here.
*/
int
max_of_four(int a, int b, int c, int d)
{
int m = a;
if (b > m)
m = b;
if (c > m)
m = c;
if (d > m)
m = d;
return m;
}
int
main(void)
{
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\n", ans);
return 0;
}
Upvotes: 2
Reputation: 17
Okey So I got it working thanks to thanatonian2311. Here is the code:
#include <stdio.h>
/*
Add `int max_of_four(int a, int b, int c, int d)` here.
*/
int max_of_four(int a, int b, int c, int d){
int result = 0;
if ((c > a) && (c > b) && (c > d)) {
return c;
} else if ((a > b) && (a > c) && (a > d)){
return a;
} else if ((b > a) && (b > c) && (b > d)){
return b;
} else if ((d > a) && (d > b) && (d > c)){
return d;
}
return result;
}
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;
}
Upvotes: -1
Reputation: 339
There are two solutions to your problem (assuming that we want to keep your logic for max_of_four intact which seems wrong):
#include <stdio.h>
/*
Add `int max_of_four(int a, int b, int c, int d)` here.
*/
void max_of_four(int a, int b, int c, int d){
// You print the answer here but don't return anything.
// main() does not expect anything when calling max_of_four(..)
if ((c > a) && (c > b) && (c > d)) {
printf("%d", c);
}
}
int main() {
int a, b, c, d;
scanf("%d %d %d %d", &a, &b, &c, &d);
max_of_four(a, b, c, d);
return 0;
}
#include <stdio.h>
/*
Add `int max_of_four(int a, int b, int c, int d)` here.
*/
int max_of_four(int a, int b, int c, int d){
// You don't print the answer here but just return the
// value of c. Please note, you still don't know what to do
// when c does not satisfy the condition
if ((c > a) && (c > b) && (c > d)) {
return c;
}
}
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;
}
Upvotes: 1