Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programming: Principles and Practice Using C++ chapter 4 drill step 6 : General question about numeric range

Tags:

c++

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.

like image 455
Kikizork Avatar asked Dec 31 '22 22:12

Kikizork


1 Answers

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>.

like image 66
Fureeish Avatar answered Jan 14 '23 01:01

Fureeish