Reputation: 225
I read a double
value using std::cin
from the keyboard, let the value be 1.15 . When I place a break point after reading the value visual studio showed that value as 1.14999999. But If I print it It printed 1.15 on my console. Later I wrote following code and it did not work well
int main()
{
long double valueA;
int required;
std::cin>>valueA;
required=(valueA*10000)-(((int)valueA)*10000);
std::cout<<(required);
}
When the input is 1.015 the output is 149 but the expected output is 150. Why is my compiler considering 1.015 as 1.014999999? How can I correct that error?
Upvotes: 1
Views: 55
Reputation: 1065
What you are describing is floating point error. This happens because of the way floating point is represented at the hardware level (see here). Basically a floating point number is kept as sme and is reconstructed as s * m * 2 ^ e where ^ is to the power of and s is 1 if the s bit is 0 and -1 if the s bit is 1.
If you need the sort of accuracy, you can use a decimal arithmetic library, it's more or less the same thing, but instead of using powers of 2, they use powers of 10 and because they are implemented in software, it means they can have arbitrary precision (more on that here).
Here's a list of libraries that implement decimal arithmetic that you can use:
Upvotes: 2