So I'm a freshman CS major and currently on spring break, and I'd figure I could do a few simple programs in my textbook to practice and try to improve as time goes on.
This program I'm having trouble with involves the user typing in integers, and the input ends when the user enters 0. After that, the program should calculate the amount of negative numbers, positive numbers, and the total amount of numbers.
I feel like I'm almost there, but could anybody explain why when I compile, no matter what numbers I enter, the output for positive/negative numbers and total is 0?
#include<iostream>
#include<iomanip>
#include<string>
usingnamespace std;
int main()
{
int positiveNum = 0;
int negativeNum = 0;
int numbers, total;
double average;
while (numbers != 0)
{
if (numbers > 0)
positiveNum++;
elseif (numbers < 0)
negativeNum++;
}
total = total + numbers;
numbers++;
cout << "Enter an integer, the input ends if it is 0: ";
cin >> numbers;
cout << "The number of positives is " << positiveNum << endl;
cout << "The number of negatives is " << negativeNum << endl;
cout << "The total is " << total << endl;
return 0;
}
On line 11 you do declare variable numbers, but do not set its value. The value is undefined. Could be anything.
Right after that a loop start and you compare Nobody knows what to 0. The value of numbers does not change within the loop. In other words, if numbers is not 0, then the loop continues infinitely. You are (un)lucky that in your tests numbers has been 0 and the loop is skipped.
On line 22 you add 'total' (unknown value) and 'numbers' (unknown value, but must be 0 if you got this far) together.
On line 26 your program reads one integer value from user. Only one.
Line 14 should probably read: while ( std::cin >> numbers && 0 != numbers )