【发布时间】:2024-04-28 10:45:01
【问题描述】:
我是 C 新手,正在尝试编写一个比较 3 个数字并返回最大数字的超级基本程序。
但是当我尝试使用 if 函数打印一些文本时,它会跳过 2 if 并转到 else。我可能会说它比它更复杂。 :)
好的,这是我的代码:
#include <stdio.h>
int a;
int b;
int c;
int max(int a, int b, int c) {
if (a>b && a>c) {
return a;
}
else if (b>a && b>c) {
return b;
}
else {
return c;
}
}
int main()
{
int d;
d = max(44,8,16);
if (d==a) {
printf("a");
}
else if (d==b) {
printf("b");
}
else {
printf("c");
}
}
它只显示“c”。没有其他的。在 if 函数中我应该写什么才能根据“max”函数中的返回值看到“a”、“b”和“c”字符?
我想保持最大功能不变。那么这样的事情有可能做到吗?
提前谢谢..
【问题讨论】:
-
a、b和c未初始化。你觉得a或b有什么价值? -
将你的全局变量移到 main 中,给它们赋值 44、8、16,然后将变量传递给函数。
-
为了简化,怎么样:
int max(int a,int b,int c) { int ret = a; if (b > ret) ret = b; if (c > ret) ret = c; return ret; }这有点笼统,如果我们有,可以很容易地扩展:int max(int a,int b,int c,int d) { ... } -
在你的主函数变量a、b、c中没有赋值。
标签: c if-statement return return-value