This question already has answers here:
Closed 7 months ago.
Scanf/Printf double variable C
(3个答案)
我正在尝试编写一个程序,用户可以从华氏温度转换为摄氏温度或摄氏温度转换为华氏温度。当我运行程序时,我输入68,它返回-17.78,而不是像它应该返回的20。
我浏览了很多不同的论坛,唯一能找到的解决方案是将数据类型从整数改为双精度,但我已经做到了。
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;

在纸上,我觉得一切都是正确的,有什么我遗漏了吗?

最佳答案

为什么我的方程式不能把华氏温度转换成摄氏温度呢?
编译器警告未完全启用。
scanf("%f", ...);需要一个float *,而不是提供的double *
"%.2f"-->中的精度是未定义的行为简单的放下scanf()不提供精度限制输入。

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

scanf("%lf", &temp);

我建议在你的scanf()中拖尾'\n'
// printf("The temperature in Celsius is %.2f.", temp);
printf("The temperature in Celsius is %.2f.\n", temp);

09-26 09:32