【问题标题】:Find largest number (C) - Code not working查找最大数 (C) - 代码不起作用
【发布时间】:2018-11-26 22:02:42
【问题描述】:

我需要用户输入三个数字,我的程序需要显示这些数字中最大的一个。我似乎无法弄清楚问题所在。我得到的结果是 "最大的数是 0.000"

#include <stdio.h>

int main()
{

double n1, n2, n3;

printf("Enter your three numbers: ");
scanf("%1f %1f, %1f", &n1, &n2, &n3);

if (n1>= n2 && n1>= n3)
    printf("The greatest number is %f", n1);

if (n2>=n1 && n2>= n3)
    printf("The greatest number is %f", n2);

if (n3>=n2 && n3>=n1)
    printf("The greatest number is %f", n3);


return 0;
}

【问题讨论】:

  • 确保您已启用编译器上的所有警告。许多现代编译器可以警告无效的转换说明符。
  • 对我来说,这个%1f 看起来像是一个错字——1 应该是一个l——就像在long 中一样——你正在扫描双精度,并指定浮点数。
  • 调试时的良好第一步: 0) 启用编译器警告并将警告视为错误; 1) 使用硬编码数据而不是用户输入开始测试; 2) 验证用户输入是否产生了您认为它产生的结果。

标签: c


【解决方案1】:

编译器知道!

$ gcc -Wall temp.c
temp.c:9:23: warning: format specifies type 'float *' but the argument has type 'double *' [-Wformat]
scanf("%1f %1f, %1f", &n1, &n2, &n3);
       ~~~            ^~~
       %1lf
temp.c:9:28: warning: format specifies type 'float *' but the argument has type 'double *' [-Wformat]
scanf("%1f %1f, %1f", &n1, &n2, &n3);
           ~~~             ^~~
           %1lf
temp.c:9:33: warning: format specifies type 'float *' but the argument has type 'double *' [-Wformat]
scanf("%1f %1f, %1f", &n1, &n2, &n3);
                ~~~             ^~~
                %1lf
3 warnings generated.

【讨论】:

  • 编译器不知道的是,用 1 指定最大字段宽度可能不是预期的。也许添加关于 %lf%1lf 的注释。
【解决方案2】:

正如 Vorsprung 所说,您需要正确的阅读/显示格式,所以:

#include <stdio.h>

int main()
{

    double n1, n2, n3;

    printf("Enter your three numbers: ");
    scanf("%lf %lf, %lf", &n1, &n2, &n3);

    if (n1>= n2 && n1>= n3)
            printf("The greatest number is %lf", n1);

    if (n2>=n1 && n2>= n3)
            printf("The greatest number is %lf", n2);

    if (n3>=n2 && n3>=n1)
            printf("The greatest number is %lf", n3);


    return 0;
}

【讨论】:

    猜你喜欢
    • 2015-03-31
    • 2023-02-22
    • 2015-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-18
    相关资源
    最近更新 更多