警告:'totalTemp' 可能会在这个函数中使用未初始化的并且 cout 不会打印到控制台

warning: 'totalTemp' may be used uninitialized in this function and cout not printing to console

尝试编写一个显示 24 小时平均温度的程序,由用户每小时输入温度。但是,我只是在代码块中收到此错误:

警告:'totalTemp' 可能未初始化地用于此函数 [-Wmaybe-uninitialized]|。

并且 运行 时控制台只是黑色,不显示任何内容。


#include <iostream>

using namespace std;

int main(void)

{
int i = 0;
while(i <= 24);
int newTemp;
int totalTemp;
{
    cout << "Input temperature for the hour " << i << ":";
    cin >> newTemp;
    totalTemp = totalTemp + newTemp;
    i++;
    cout << "The average temperature for the day is " << totalTemp/24 << " degrees";

}
 return (0);
}


如何初始化它?当我尝试使用 cout 时,是什么导致我的代码没有出现在控制台中?

How do I initialize it?

int totalTemp = 0;

and what is making my code not appear in the console when I'm trying to use cout?

while(i <= 24);

这是一个空体的无限循环。没有可观察到的副作用的无限循环是未定义的行为。允许编译器为您的代码生成与 int main() {} 相同的输出。你可能想要 while( i<=24) { ...。或者当迭代次数固定时使用 for 循环。

此外,totalTemp/24 正在使用整数运算。也许这就是您想要的,但您更有可能想要 totalTemp/24.0。而且您很可能希望在循环外打印平均值,而不是在每次迭代中打印它。