Reputation: 19
#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.
Upvotes: 1
Views: 232
Reputation: 5321
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";
}
}
Upvotes: 1