C:将Farenheit转换为Celsius
int main (void) { int fahrenheit; // fahrenheit stands for fahrenheit double c; // c stands for celsius printf("Enter your fahrenheit, we'll covnvert it into celsius! "); scanf("%f", &fahrenheit); c = 5/9 * (fahrenheit - 32); printf("Here is your %f in celsius!.\n"); return (0); }
我通过断点跟踪代码,当它输入我的输入时计算结束,但公式是正确的。 某种逻辑错误,我无法指责。 请帮忙!
scanf
调用使用错误的格式字符串。 你正在读一个int
所以你需要它:
scanf("%d", &fahrenheit);
使用整数除法评估表达式5/9
。 事实上,编译器可以在编译时解决它。 该表达式的计算结果为0
。
您需要执行浮点除法。 例如:
5.0/9
要么:
5/9.0
要么
5.0/9.0
您只需要至少一个操作数作为浮点值。
把它放到你的表达式中,你可以写:
c = 5.0/9.0 * (fahrenheit - 32);
并获得您期望的答案。
你的printf
语句也是错误的。 您应该启用警告并让编译器告诉您。 你打算写:
printf("Here is your %f in celsius!.\n", c);
整数数学与浮点数学。
i = 5/9 // i is equal to 0 d = 5.0/9.0 // d is equal to whatever 5 divided by 9 would actually be
您还需要实际打印该值:
printf("Here is your %f in celsius!.\n", c);
简答:即使存储结果的变量是double,整数运算也会返回整数。 整数之间的划分被截断。
你应该写这个:
c = 5.0/9.0 * (fahrenheit - 32.0);
在常量中添加“.0”(或者甚至只是“。”)会使它们成为浮点值。