I've been following a C++ tutorial, and I always try to play around with each one to get a better understanding. This program just takes a set of numbers and calculates the average. When I perform the calculation in a cout statement, I get the results I expect, however if I assign the calculation to a variable I get some extremely strange results. I have no idea why.
int age;
int ageTotal = 0;
int numberOfPeople;
cout << "Enter an age, or enter -1 to quit: ";
cin >> age;
while (age != -1) {
ageTotal = ageTotal + age;
numberOfPeople++;
cout << "Enter an age, or enter -1 to quit: ";
cin >> age;
}
cout << "Number of people entered: " << numberOfPeople << endl;
cout << "The average age is: " << ageTotal / numberOfPeople;
// If I add this code, I get unexpected results
//int average = 0;
//average = ageTotal / numberOfPeople;
//cout << "Variable average is: " << average;
Results without assigning average to variable:
1 2 3 4 5
Enter first persons age or -1 to quit: 10
Enter next persons age, or -1 to quit: 10
Enter next persons age, or -1 to quit: -1
Number of people entered: 2
The average age of people entered is: 10
Results when I do assign the average to variable:
1 2 3 4 5 6
50 Enter first persons age or -1 to quit: 10
51 Enter next persons age, or -1 to quit: 10
52 Enter next persons age, or -1 to quit: -1
53 Number of people entered: 4197138
54 The average age of people entered is: 0
55 Variable average is: 0
@helios, thank you so much. Defining it did fix the problem.
I still don't totally understand why though. If an uninitialized incremented variable is undefined, then why does it return the expected values on lines 16 and 17? Does C++ store variable values in a stack like Java? Is it that it's referencing the value in the stack, but hasn't been assigned a space in memory?