all real numbers

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
	int number, sum = 0, counter = 0, avg = 0, p1, p2max = -1000000, p2min = 10000000;
	inputFile.open("random1.txt");

	if (inputFile)
	{

		while (inputFile >> number)
		{
			p1 = number;
			sum += p1;
			counter++;
			avg = sum / counter;
			if (p1 > p2max)
			{
				p2max = p1;
			}
			if (p1 < p2min)
			{
				p2min = p1;
			}
		}



The problem that im having is making it so p2max and p2min can hold all real numbers to reference p1 with to find an accurate number no matter if the input from the file is all negatives or positives. Ie without using hardcoded numbers in the int.

any help would be great.
One strategy would be to read the first number in the file and set it to be the maximum and minimum so you don't need to have an initial value.

You could also use std::numeric_limits<int>::min() and std::numeric_limits<int>::max() to get the smallest and largest values representable by an int, respectively. These are in the header <limits>.
http://www.cplusplus.com/reference/limits/numeric_limits/
I see, so essentially

p1 = p2max = number;

does work, however what about minimum without forcing a numerical limit?
Read the first number and assign it as both the maximum and minimum. It works for both. You will want to only do this on the first read, however, otherwise you will overwrite your maximum and minimum every iteration of the loop.
Okay so I technically would need to nest it into a process that only proceeds once, then loops the calculations separate with those values. Is that correct?
Is there any place to put that statement p2min = p2max = number; in the loop and number is inititalized at the while (inputFile >> number) statement? without of course defining it more than the first time.
Last edited on
got my answer, thanks for the help. if (counter == 0) p2min = p2max = number;
Last edited on
Topic archived. No new replies allowed.