Program not behaving as expected.

Hi guys,

I am working on an exercise whereby after reading in sequence of values, I need to print the total sum, the greatest and the smallest values. The code below seems to do the trick, although for the min value, it always churns out 0 for some reason. Am I missing anything?

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
  int main()
try
{
	vector<double> dist;

	double sum = 0;	
	double min = 0;	
	double max = 0;

	cout << "please enter a whitespace-separated sequence of doubles: " << flush;
	double val = 0;
	while (cin >> val) {	
		
		if (val <= 0) {
			if (dist.size() == 0) error("no distances");
			cout << "total distance " << sum << '\n';
			cout << " smallest distance " << min << '\n';
			cout << "greatest distance " << max << '\n';
			cout << "mean distance " << sum / dist.size() << '\n';
			
			return 0;	
		}
		dist.push_back(val);	

		sum += val;
		if (val<min) min = val;
		if (max<val) max = val;
	}
	if (dist.size() == 0) error("no distances");
	cout << "total distance " << sum << '\n';
	cout << " smallest distance " << min << '\n';
	cout << "greatest distance " << max << '\n';
	cout << "mean distance " << sum/dist.size() << '\n';
	
}
catch (runtime_error e) {	
	cout << e.what() << '\n';
	
}
catch (...) {	 
	cout << "exiting\n";
}
Last edited on
The min variable is initialized to 0 so unless you input a negative value it will not get updated. You have the same problem with the max variable if the user only inputs negative numbers.
Thanks, although I've had already thought about this issue; I need to initialize both variables with something though otherwise I get an error. My max variable gets updated anyway, but not min....
A common technique in this kind of situation is to initialize the variable to a very large value, preferably the largest possible value that the type can hold. Floating point type usually has a special value for infinity that will compare greater than any finite value.

http://en.cppreference.com/w/cpp/types/numeric_limits/infinity
Last edited on
Thanks Peter, I'll give that a try.
Peter, You're a genius, it worked!! I used double inf = std::numeric_limits<double>::infinity();
Thanks for taking the time to have a look at my code.
Last edited on
Topic archived. No new replies allowed.