output doesn't show following do/while loop

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
using namespace 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;
		else
		if (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?

Thanks
Last edited on
Also, I have no idea if that formula to calculate average is correct (I think it is, though)
Last edited on
How did this compile for you? INT_MAX and INT_MIN are constants defined in limits.h. You need to find different variable names.
Last edited on
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
Last edited on
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?
Last edited on
The program ends - the console is still there
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....
Just fix the errors I've pointed out and you should be good.
Topic archived. No new replies allowed.