首页 > 解决方案 > 期望从 while 循环中输出四个打印输出,只得到一个

问题描述

我正在尝试使用 while 循环编写一个程序,该循环根据声明的输入变量的范围给出输出。

#include <iostream>
using namespace std;
  
int main() {
    
    float fahren = 0;
    float celsius;
  
    while (fahren < 400) {
        // convert fahreneheit to celsius 
        // Subtract 32, then multiply it by 5, then divide by 9
         
        celsius = 5 * (fahren - 32) / 9;
        cout << celsius;
        fahren+= 100;
    }
    return 0;
}

我希望返回 4 个值,但我只得到 1,即 0 处的值。

标签: c++while-loop

解决方案


您打印 4 个值但没有分隔符,您可以添加std::cout << std::endl;

while (fahren < 400) {
    // convert fahreneheit to celsius 
    // Subtract 32, then multiply it by 5, then divide by 9
     
    celsius = 5 * (fahren - 32) / 9;
    std::cout << celsius << std::endl; // added new line here
    fahren += 100;
}

演示


推荐阅读