1
#include <iostream>
#include <sstream>

using namespace std;
using std::stringstream;
using std::cout;

int main()
{
    double value;
    cout << "Enter a number : " << endl;
    cin >> value;
    cout << "The exact number : ";
    cout << value << endl;
    system("pause");
}

After i wrote this code, i found out that the double of every variable will rounded off in the IF ELSE statement, how can i take the exact value of input to the IF ELSE statement? For example: The input is 0.007447 and if input is less than or equal to 0.007447 it will prompt another input. But in this case, after the user input is 0.007447 and it will be rounded off to 0.00745, Thus it will runs the else statement but not the if statement.

  • `sampleV` is a long double. `0.007447` is a double. Does it make any difference if you use a long double constant? – Eljay Oct 10 '19 at 13:00
  • 1
    Do you really need *all* that code to demonstrate your problem? Please read about the [mcve]. – molbdnilo Oct 10 '19 at 13:06
  • Don't mix precisions when using floating point. Reading 0.007447 into a `long double` does not give you the same approximation as converting the `0.007447` literal (which denotes a `double`). And neither is exactly 0.007447, because it can't be represented exactly in binary floating point. – molbdnilo Oct 10 '19 at 13:08
  • Because of double/float imprecision, checking if doubles are equal must be done by checking if they are really close to each other. As "really close" is not an exact definition, there exist several approaches to this, see https://stackoverflow.com/questions/17333/what-is-the-most-effective-way-for-float-and-double-comparison – Aziuth Oct 10 '19 at 14:14

1 Answers1

1

On my platform, changing the constant to be a long double constant fixed the misbehavior.

Floating points numbers (float, double, long double) are not mathematically real numbers. Rather than have limited precision.

More details at What Every Computer Scientist Should Know About Floating-Point Arithmetic .

Also, your example was much larger than you needed it to be. A minimal example could be easily expressed like this (including the "fix"):

#include <iostream>
#include <sstream>

using std::stringstream;
using std::cout;

int main() {
    long double value;
    stringstream ss("0.007447");
    ss >> value;
    if (value <= 0.007447) {
        cout << "value <= 0.007447 ==> TRUE -- as expected\n";
    } else {
        cout << "value <= 0.007447 ==> FALSE -- unexpected!\n";
    }

    if (value <= 0.007447L) {
        cout << "value <= 0.007447L ==> TRUE -- as expected\n";
    } else {
        cout << "value <= 0.007447L ==> FALSE -- unexpected!\n";
    }
}
Eljay
  • 4,648
  • 3
  • 16
  • 27