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...
int main()
{
constexprdouble cm_per_meter = 100.0;
constexprdouble ft_per_meter = 3.2808;
constexprdouble 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;
elseif (unit == "ft") val /= ft_per_meter;
elseif (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.
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.