最后我一直收到 0 作为我的答案。请帮忙
#include <stdio.h>
int Fahrenheit = 0;
double Celsius = 0.0;
double main(void)
{
printf("This program will convert the temperature from fahrenheit to celsius.\n");
printf("Please type in the temperature in fahrenheit followed by the enter key.\n");
scanf("%d%",&Fahrenheit);
Celsius = (5/9) * (Fahrenheit-32) ;
printf("Your temperature in celsius is %3.2f.\n", Celsius);
return(0);
}
最佳答案
由于整数除法,将5/9
更改为5.0/9.0
。另外,将 Fahrenheit
double
并将 scanf()
更改为
if (scanf("%lf", &Fahrenheit) == 1)
{
Celcius = 5.0 * (Fahrenheit - 32.0) / 9.0;
printf("Your temperature in celsius is %3.2f.\n", Celsius);
}
另外:
- 绝对没有理由将变量设置为全局变量。
我看到了许多奇特的
main()
签名,现在double main(void);
忽略
scanf()
的返回值将导致潜在的未定义行为。如果我有一位老师禁止if
语句但需要scanf()
,我会放弃他并找到一位好的老师。但是当然,如果我正在学习,我怎么知道忽略 ٰ
scanf()
的返回值是不好的?这就是可悲的部分,许多人甚至不知道它返回一个值或它失败,例如尝试这个int value; if (scanf("%d", &value) != 1) fprintf(stderr, "Error, invalid input\n"); else fprintf(stdout, "Ok, so your input is `%d'\n", value);
输入
“abcd”
而不是数字,会发生什么?
关于c - 不断得到 0.00 作为答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35257538/