How to find Min,Max, and Avg without arrays in program.

This program does everything i want except for one major problem and one small one.
1. The program keeps taking my last entered number and counting it as max and min
2. When I go to end with 0 it adsd the enter number prompt then returns.
_________________________________________________________________________________

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
31
32
33
34
35
36
#include <iostream>
using namespace std;

int main()
{
	int Nset, count;
	double min = 10, max = 0, Average, sum = 0, numbers;
		cout.setf(ios::fixed); 
		cout.setf(ios::showpoint);
		cout.precision(3);
	do{
	do{
	cout <<"Please enter the size of the data set (1-10 elements or 0 to quit): "<< endl;
	cin >> Nset;
	cout << "Enter Number: " << endl;
	if (Nset == 0){
	return 0;} 	
	} while (Nset<=0 || Nset >10);
	for (count=1; count<= Nset; count++) {
		cin >> numbers;
		min = max = numbers;
		sum = sum + numbers;
		Average = sum / Nset;
		if (numbers < min)
		min = numbers;
	if (numbers > max)
		max = numbers;
	}
cout << "The highest number is " << max << endl;	
cout << "The lowest number is " << min << endl;
cout << "average = " << Average << endl;
sum = 0;
	}while (true);
return 0;
	
}
Hi,

One immediate thing I can see:

Get rid of line 2 - std::count, std::min and std::max all exist in the std namepace, so it is possible this might cause conflicts with your variable names. This is one of the reasons line is bad practice - I wish book authors & lecturers would quit doing it.

Edit: Use std::cout, std::endl because you now don't have the entire std namespace in the global namespace. This is how one refers to individual items in a namespace.

Always initialise your variables - preferably declare & initialise one variable per line.

line 19: the normal idiom is:

for (ItemNum=0; ItemNum< Nset; ItemNum++) {

Avoid using infinite loops - you should always have an end case - make that your condition.

Line 22: Try this

sum += numbers;

As for the problems - think about the position of lines 15 and 16 in your code relative to what happens after that.

Hope all is well :+)
Last edited on
Topic archived. No new replies allowed.