Home > OS >  warning: 'totalTemp' may be used uninitialized in this function and cout not printing to c
warning: 'totalTemp' may be used uninitialized in this function and cout not printing to c

Time:03-07

Trying to write a program displaying the average temperature in 24 hours, by the user typing in the temperature each hour. However, I'm just getting this error in code blocks:

warning: 'totalTemp' may be used uninitialized in this function [-Wmaybe-uninitialized]|.

and the console is just black when ran and not displaying anything.


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


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

CodePudding user response:

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);

This is an infinite loop with an empty body. Infinite loops without observable side effects are undefined behavior. The compiler is allowed to produce the same output for your code as it would for int main() {}. You probably want while( i<=24) { .... Or rather use a for loop when the number of iterations is fixed.

Moreover, totalTemp/24 is using integer arithmetics. Maybe thats what you want, but more likely you want totalTemp/24.0. And also very likely you want to print the average outside of the loop instead of printing it in every iteration.

  • Related