"while()"功能?

Ste*_*043 6 c while-loop

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

#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;
    }
}
Run Code Online (Sandbox Code Playgroud)

正如我在源代码中所提到的那样,当我尝试将摄氏公式放入main()函数体中时,我会得到-17.8每一个华氏值.输出看起来像这样 -

0 -17.78
5 -17.78
10 -17.78
15 -17.78
20 -17.78
25 -17.78
Run Code Online (Sandbox Code Playgroud)

等等等等.但是,当我将摄氏公式放入while()函数中时,我会得到每个华氏度值的正确摄氏值.它看起来像这样:

0 -17.78
5 -15.00
10 -12.22
15  -9.44
20  -6.67
Run Code Online (Sandbox Code Playgroud)

为什么会这样?

这是不起作用的代码.除了摄氏公式的位置外,它与上面的代码相同.(至少,我认为是.)

#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;
    }
}
Run Code Online (Sandbox Code Playgroud)

kev*_*nji 7

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

celsius = (fahrenheit - 32.0) * 5.0/9.0;
Run Code Online (Sandbox Code Playgroud)

外的的while环路,它使用的当前值fahrenheit(即0.0),并且计算该值celsius,这是-17.78.

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