【问题标题】:want to print the max integer out of four integer but extra 1 is added to the result [closed]想要打印四个整数中的最大整数,但在结果中添加了额外的 1 [关闭]
【发布时间】:2022-07-29 20:46:35
【问题描述】:

当我运行程序时,如果答案是 4,它会给出输出 41。 我是编程新手,对 c 了解不多。

 #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;
    }

【问题讨论】:

  • 请正确格式化您的代码以使其可读。您可以通过单击下面的edit 来编辑您的问题并在此处获得编辑帮助:stackoverflow.com/editing-help
  • 另外添加一个具体问题,以及有关您的代码的具体问题的详细信息。

标签: c


【解决方案1】:

这是因为您返回并打印了 printf() 的值,它只打印了 1 个字符。您只需要返回数字而不是printf() 的结果。

另外,请始终检查scanf() 是否成功。

最终代码

#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));
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多