1
#include "stdafx.h"
#include "../../std_lib_facilities.h"




int main()
{
    double val1 = 0;
    double val2 = 0;

    cout << "Please enter 2 values seperated by a space\n";

    while(cin >> val1 >> val2) {
        if (val1 > val2) {
            cout << val1 << " is the larger value\n";
        }
        else if (val2 > val1) {
            cout << val2 << " is the larger value\n";
        }
        else {
            cout << " values are equal\n";
        }

        double res1 = val1 - val2;
        double res2 = val2 - val1;
        cout << res1 << "," << res2 << "\n";
        if ((res1 < 0.01 && res2 < 0.01) && val1!=val2) {
            cout << " Values are almost equal\n";
        }
    }

    return 0;
}

the problematic part is the last if statement(even if val1!=val2 is taken out the problem persists). so if the input differs by 0.009 or 0.02 it works well for all numbers but when the difference is exactly 0.01 it only works for 0, 0.01 and 1 1.01 , anything above that (ie 10, 10.01) prints out the cout line. i wonder why is that and what is the problem? is it possible to fix it without using math functions?

Edit: Goran Flegar thank you! your comment helped to understand the problem! So what would be the way to get around this and actually compare " print "numbers are almost equal " when the difference is smaller than 1.0/100" is there a way to do it with simple arithmetic?

Kirill
  • 23
  • 3
  • 1
    There is no such floating point value as the decimal value 0.01. There is a binary value close to it. – stark Apr 14 '18 at 12:56
  • I wouldn't agree it's a complete duplicate. What other questions don't explain is that `std::cout` will round the value before printing it out and make it look "nice", even though that's not the value stored in memory. You can see that just by adding `std::cout << std::scientific << std::setprecision(17)`. – gflegar Apr 14 '18 at 13:03

0 Answers0