gpt4 book ai didi

c - "while()"功能?

转载 作者:太空狗 更新时间:2023-10-29 17:18:22 25 4
gpt4 key购买 nike

这个程序应该将华氏度转换为摄氏度:

#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;
}
}

正如我在源评论中指出的那样,当我尝试将摄氏度公式放入 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;
}
}

最佳答案

当您为变量设置值时,会计算实际值,然后将其存储到变量中。但是,您不会存储变量的公式。因此,当你运行时

celsius = (fahrenheit - 32.0) * 5.0/9.0;
while 循环的

之外,它使用 fahrenheit 的当前值(即 0.0),并计算 的值>摄氏度,即 -17.78。

while循环中,虽然fahrenheit改变了,但是celsius不会改变,因为里面没有语句while 循环实际改变变量的值。这就是为什么您必须将语句移动到 while 循环中,以确保每次 fahrenheit 值更改时 celsius 值都会更新。

关于c - "while()"功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27454267/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com