[英]My function returns a annoying zero to my output
我的 function (max_of_four) 需要return;
代码,但通过添加它,我的 output 也得到了一个零,这是我不想要的。 我只想打印 int c(数字 6)的内容。
这是代码:
#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;
}
请帮我只打印 integer c (6),不带零(现在看起来像 60)。
在max_of_four
中,您只有 [only] return;
. 您需要一个return
值的 return
您可能不希望printf
中的 printf (即)它是调试printf
。
如果我们相信您的 function 的名称,则 function 必须比较所有值以获得最大值。
这是一些重构的代码:
#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;
}
您的问题有两种解决方案(假设我们希望保持您的 max_of_four 逻辑完整,这似乎是错误的):
#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;
}
好吧,多亏了thanatonian2311,我才让它工作起来。 这是代码:
#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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.