Initializing "smallest" and "largest" values

I have this trivial program I'm writing, and everything seems to work just fine. However, I am bothered by the code I have written for "smallest" and "largest", which is show below...

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
int main()
{
	constexpr double cm_per_meter = 100.0;
	constexpr double ft_per_meter = 3.2808;
	constexpr double in_per_meter = 39.37;

	vector<double> values;

	double val{ 0 };
	string unit;

	double smallest{ 10000000 };
	double largest{ -10000000 };
	double sum{ 0 };

	cout << "Enter a floating-point value followed by a unit.\n"
		<< "(cm, m, in, ft)\n> ";

	while (cin >> val >> unit) {
		if (unit != "m" && unit != "cm" && unit != "ft" && unit != "in")
			cout << "Invalid unit.\n";
		else{
			if (unit == "cm") val /= cm_per_meter;
			else if (unit == "ft") val /= ft_per_meter;
			else if (unit == "in") val /= in_per_meter;

			values.push_back(val);

			if (val < smallest) {
				smallest = val;
			}
			if (val > largest) {
				largest = val;
			}

			sum += val;
		}
	}

	sort(values);
	for (double val : values)
		cout << val << "\n";

	cout << "Largest: " << largest << "m\n"
		<< "Smallest: " << smallest << "m\n"
		<< "Sum: " << sum << "m\n";

	keep_window_open();
	return 0;
}


Is there any clean way for me to initialize smallest and largest on the first round of input without undermining their purpose (to store the largest and smallest values seen up to that point)? I don't like having them set to arbitrary values, and considering any input larger or smaller than the ones I have set will result in a runtime error.

Note* I know I have I shouldn't have all my code packed into main, but I was just screwing around with something, so I didn't bother to cohere with proper programming organization techniques.
Last edited on
If the double type on your computer has support for infinity (std::numeric_limits<double>::has_infinity == true), which is probably the case, you could initialize the variables to infinity and negative infinity.

1
2
double smallest{ std::numeric_limits<double>::infinity() };
double largest{ -std::numeric_limits<double>::infinity() };

Another solution that doesn't require infinity is to initialize them to the highest and lowest possible finite values that a double can store.

1
2
double smallest{ std::numeric_limits<double>::max()    };
double largest{  std::numeric_limits<double>::lowest() };
Last edited on
Sounds good. I haven't worked with numeric_limits too much. This seems helpful though, thank you.
Topic archived. No new replies allowed.