Finding the largest and smallest integer in a set using while loop

I've been working at this for awhile and it seems like it should be correct but it isn't giving me the desired output. Here's my code.
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
37
38
39
40
41
42
43
44
45
46
47
48
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <iomanip>

using namespace std;

void main()
{
	string dataFile("ExamScores.txt");
	ifstream fin;

	fin.open(dataFile);

	int s(0), ns(0), sns(0);
	int total_score(0);
	int max = s;
	int min = s;

	fin >> s;


	while( ! fin.eof() )
	{
		++ns;

		total_score += s;

		if(s > max)
		{
			max = s;
		}
		
		if(s < min)
		{
			min = s;
		}

	
		fin >> s;
	}//end file read loop
	cout << total_score/ns << endl;
	cout << "Max: " << max << endl;
	cout << "Min: " << min << endl;
	fin.close();


}

And here is my output when I run the program.
75
Max: 90
Min: 0
Press any key to continue . . .
I am reading from a file in this program which contains a set of 30 numbers and it has the average correct and the max correct but the minimum number in the set is 56 however it keeps giving me a zero for the min. Any help is appreciated.
you need to initialise min to be a very large number.
I actually did that afterwards. I initialized it to 56 because it's the only reason I could think of why I keep getting zero although I'm not sure if that's proper programming but it's all I've got for now. Thanks for the help!
well, if the highest realistic exam score is 100, you could initialise 'min' to 100. i.e. the maximum value your 'min' variable could ever be. If that makes sense? :)
Last edited on
closed account (48T7M4Gy)
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <iomanip>

using namespace std;

void main()
{
	string dataFile("ExamScores.txt");
	ifstream fin;

	fin.open(dataFile);

	int s(0), ns(0), sns(0);
	int total_score(0);
        int s, max;//

	//int max = s;
	//int min = s;

	 fin >> s;

	max = s;
	min = s;


	while( ! fin.eof() )
	{
		++ns;

		total_score += s;

		if(s > max)
		{
			max = s;
		}
		
		if(s < min)
		{
			min = s;
		}

	
		fin >> s;
	}//end file read loop
	cout << total_score/ns << endl;
	cout << "Max: " << max << endl;
	cout << "Min: " << min << endl;
	fin.close();


}
Last edited on
Topic archived. No new replies allowed.