为什么我的等式不能用于将华氏温度转换为摄氏温度? [重复]

问题描述 投票:1回答:2

这个问题在这里已有答案:

我正在尝试编写一个程序,用户可以将华氏温度转换为摄氏温度或华氏摄氏温度。当我运行程序时,我输入68并返回-17.78而不是它应该的20。

我查看了很多不同的论坛,我能找到的唯一解决方案是将数据类型从整数更改为double但我已经这样做了。

double temp;

printf("Input temperature in degrees Fahrenheit:");
scanf("%.2f", &temp);
temp = (5.0f/9.0f)*(temp-32.0f);
printf("The temperature in Celsius is %.2f.", temp);
return 0;

在纸面上,在我看来,一切都是正确的,是否有我遗漏的东西?

c
2个回答
5
投票

为什么我的等式不能用于将华氏温度转换为摄氏温度?

编译器警告未完全启用。


scanf("%f", ...);期待一个float *,而不是double *提供。

"%.2f" - > scanf()的精确度是未定义的行为。简单的下降。 scanf()不提供精度限制输入。

double temp;
printf("Input temperature in degrees Fahrenheit:");
// scanf("%.2f", &temp);

scanf("%lf", &temp);

我建议你的'\n'尾随printf()

// printf("The temperature in Celsius is %.2f.", temp);
printf("The temperature in Celsius is %.2f.\n", temp);

1
投票

我改变了你的程序,一切看起来都不错:

int main()
{
    float temp;

    printf("Input temperature in degrees Fahrenheit:");
    scanf("%f", &temp);
    temp = (5.0f/9.0f)*(temp-32.0f);
    printf("The temperature in Celsius is %.2f.", temp);
    return 0;
}

也要注意编译器警告。例如,你的代码编译器说warning: C4476: 'scanf' : unknown type field character '.' in format specifier所以我从.参数中删除了scanf

© www.soinside.com 2019 - 2024. All rights reserved.