I want to prompt the user for some double, then store the smallest and largest value and then prints a text. This is the code I have so far:
#include <iostream>
#include <string>
#include <cmath>
#include <vector>
using namespace std;
int main()
{
double min = 1000000000; // Here is my issue !
double max = -100000000; // Here is my issue !
for (double input; cin >> input;)
{
if (input == '|')
return 0;
else if (input < min)
{
min = input;
cout << "The smallest so far\n";
}
else if (input > max)
{
max = input;
cout << "The largest so far\n";
}
else
cout << "\n";
}
}
So my code is working fine and doing what I want, but I have a question about the way to handle the double min and max. I must give them a value to get my program working, but giving them a value inpact the user. If I don't set them high or low enough the user might input value that don't trigger the program. So I set them up at arbitrary high/low number. But I wonder if there is a better solution for this.
If I don't set them high or low enough the user might input value that don't trigger the program.
Correct.
But I wonder if there is a better solution for this.
There is!
1000000000
may indeed be not enough. You might be interested in numeric limits. What you want is:
double min = std::numeric_limits<double>::max();
double max = std::numeric_limits<double>::lowest();
which will set both values to the greatest and smallest representable double
, respectively.
Don't forget to #include <limits>
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With