#include <iostream>
usingnamespace std;
int main ()
{
int x, a = 1, INT_MAX, INT_MIN, sum = 0;
char response;
double avg;
do
{
cout << "Enter number " << a++ << ": ";
cin >> x;
if (x > INT_MAX)
INT_MAX = x;
elseif (x < INT_MIN)
INT_MIN = x;
else
sum += x;
avg = (sum / a);
cout << "Do you want to enter another number?";
cin >> response;
}
while (response == 'y' || response == 'Y');
cout << "The smallest number is " << INT_MIN << ", and the largest number is " << INT_MAX << endl;
cout << "The average is " << avg;
return 0;
}
I essentially have a program that someone inputs numbers into until they answer 'n', then the program spits out a minimum, maximum and average value for all the numbers.
Right now the issue is that when the loop stops the output afterwards doesn't show up all all:
1 2
cout << "The smallest number is " << INT_MIN << ", and the largest number is " << INT_MAX << endl;
cout << "The average is " << avg;
This section doesn't display in the output - what I am doing wrong?
I didn't get any errors compiling this in GCC. My professor advised us to use INT_MAX and INT_MIN, but I obviously did that wrong, apparently.
Regardless - assuming that INT_MIN and INT_MAX are just normal variables and not defined constants, what I am doing wrong here? The code works for the first few commands - I can enter numbers and repeat this when I input y, but the moment I answer n the program exits
Well first of all, INT_MIN and INT_MAX are never initialized. So what number are you comparing x to?
1 2 3
else
sum += x;
avg = (sum / a);
This else is never going to execute unless x == INT_MIN or INT_MAX. Is that really what you want? You should be: sum+= x; each iteration of the loop, but if x > or < one of the variables you will miss adding that number to sum. You are also trying to figure the average potentially in each loop. avg = (sum / a ) should be outside the loop.
Napwneon wrote:
I can enter numbers and repeat this when I input y, but the moment I answer n the program exits
The program ends or the console window just closes so fast you don't see the output?
I believe it was the compiler that was the problem - switched computers, and the output showed itself. Now for trying to figure out the code itself....