Reputation: 63
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.
Upvotes: 4
Views: 419
Reputation: 13434
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>
.
Upvotes: 6
Reputation: 10982
I came too late to answer the question, however I wanted to draw your attention on that in your case you must use lowest()
and not min()
double min = std::numeric_limits<double>::max();
double max = std::numeric_limits<double>::lowest(); // <-- Attention, not min
using min()
instead of lowest()
is a common error (yes the name is misleading)
From cppreference:
lowest()
[static] (C++11) returns the lowest finite value of the given type (public static member function)
min()
[static] returns the smallest finite value of the given type (public static member function)
std::cout << std::numeric_limits<double>::min();
std::cout << std::numeric_limits<double>::lowest();
prints:
2.22507e-308 <-- min : smallest value
-1.79769e+308 <-- lowest : is what you need in your case
Upvotes: 3