“while()”功能?

前端之家收集整理的这篇文章主要介绍了“while()”功能?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
该程序应该将华氏度转换为摄氏度:
#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,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",celsius);
        fahrenheit = fahrenheit + step;
    }
}

解决方法

将值设置为变量时,将计算实际值,然后将其存储到变量中.但是,您不存储变量的公式.因此,当你跑步
celsius = (fahrenheit - 32.0) * 5.0/9.0;

在while循环之外,它使用当前的fahrenheit值(即0.0),并计算摄氏度的值,即-17.78.

在while循环中,虽然华氏度发生变化,但摄氏度不会,因为while循环内部没有任何语句可以实际更改变量的值.这就是为什么你必须将语句移动到while循环中,以确保每次华氏温度值改变时摄氏度值都会更新.

原文链接:https://www.f2er.com/c/116375.html

猜你在找的C&C++相关文章