【问题标题】:Operations with return values in C在 C 中返回值的操作
【发布时间】: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”字符?

我想保持最大功能不变。那么这样的事情有可能做到吗?

提前谢谢..

【问题讨论】:

  • abc 未初始化。你觉得ab有什么价值?
  • 将你的全局变量移到 main 中,给它们赋值 44、8、16,然后将变量传递给函数。
  • 为了简化,怎么样:int max(int a,int b,int c) { int ret = a; if (b &gt; ret) ret = b; if (c &gt; ret) ret = c; return ret; } 这有点笼统,如果我们有,可以很容易地扩展:int max(int a,int b,int c,int d) { ... }
  • 在你的主函数变量a、b、c中没有赋值。

标签: c if-statement return return-value


【解决方案1】:

您没有为abc 分配任何值。并且由于它们是全局变量,它们被隐式初始化为 0。还要注意,这些全局变量与具有相同名称的 max 的参数不同。参数掩码全局变量。

将全局变量移入main 并为其赋值,然后将变量传递给max

int main()
{
    int a=48, b=8, c=16;
    int d;
    d = max(a,b,c);
    ...

【讨论】:

  • 哦,非常感谢。在我尝试了您的解决方案后,我还尝试将 int a=48, b=8, c=16; 移至全局,它也有效!