S
S
skillfinder2018-10-31 14:52:53
C++ / C#
skillfinder, 2018-10-31 14:52:53

Why doesn't this program run exactly as I expected?

Greetings
The essence of the program is that 2 floating point numbers are entered. The script takes several paths - if one number is greater than the other and if they are equal. If one number is less than another by just less than 0.01 - then "Numbers are almost equal" is displayed, here is my code:

int main(){

    double val1, val2;

    while(cin >> val1 >> val2){
        if(val1 > val2)
            if(val1 - val2 < 0.01)
                cout << "Числа почти равны\n";
            else
                cout << "Наименьшее значение равно " << val2 << "\n"
                     << "Наибольшее значение равно " << val1 << "\n";
         else if(val1 < val2)
            if(val2 - val1 < 0.01)
                cout << "Числа почти равны\n";
            else
                cout << "Наименьшее значение равно " << val1 << "\n"
                     << "Наибольшее значение равно " << val2 << "\n";
         else
            cout << "Числа равны";
    }
    return 0;
}

What exactly is my question? If I enter 10.01 and 10.02 into the console, the output is "numbers are almost equal", although I indicated to go this way only when their difference is less than 0.01 . I understand if I made a condition , but my code does not contain such a construct if(val1 - val2 <= 0.01)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Armenian Radio, 2018-10-31
@skillfinder

Due to rounding errors, numbers are represented in doubles not quite like 10.01 and 10.02 - and you get a border case like 0.99999999998 as a difference

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question