【发布时间】:2015-02-11 18:59:30
【问题描述】:
这个程序应该将华氏度转换为摄氏度:
#include <stdio.h>
int main() {
float fahrenheit, celsius;
int max, min, step;
max = 100;
min = 0;
step = 5;
fahrenheit = 0.0;
//celsius = (fahrenheit - 32.0) * 5.0/9.0; DOESN'T WORK HERE
printf("\n");
printf("This program converts fahrenheit into celsius \n");
while(fahrenheit <= max) {
celsius = (fahrenheit - 32.0) * 5.0/9.0; /* Works here */
printf("%3.0f %6.2f\n", fahrenheit, celsius);
fahrenheit = fahrenheit + step;
}
}
正如我在源 cmets 中所指出的,当我尝试将摄氏公式放入 main() 函数的主体时,每个华氏值都会得到 -17.8。输出看起来像这样 -
0 -17.78
5 -17.78
10 -17.78
15 -17.78
20 -17.78
25 -17.78
等等等等。但是,当我将摄氏公式放入 while() 函数时,我得到每个华氏值的正确摄氏值。它看起来像这样:
0 -17.78
5 -15.00
10 -12.22
15 -9.44
20 -6.67
为什么会这样?
这是不起作用的代码。它与上面的代码相同,除了摄氏度公式的位置。 (至少,我认为是。)
#include <stdio.h>
//this program is supposed to convert fahrenheit into celsius
int main() {
float fahrenheit, celsius;
int max, min, step;
max = 100;
min = 0;
step = 5;
fahrenheit = 0.0;
celsius = (fahrenheit - 32.0) * 5.0/9.0;
printf("\n");
printf("This program converts fahrenheit into celsius \n");
while(fahrenheit <= max) {
printf("%3.0f %6.2f\n", fahrenheit, celsius);
fahrenheit = fahrenheit + step;
}
}
【问题讨论】:
-
while不是函数;它是指定特定类型语句的关键字。您问题中的代码可以正常工作。我们需要查看不起作用的代码。 -
@KeithThompson 他提供了不起作用的代码:相同的代码,但转换代码移出循环。
-
@FUZxxl:是的,他在我发表评论后编辑了问题。
-
该代码不起作用是因为仅对华氏温度的一个值执行计算,特别是当它等于 0 时。鉴于您的 cmets 和代码,我的建议是花一点学习C语言的时间
标签: c while-loop