This is a floating point arithmetic problem.
Running this:
#include <iostream>
using namespace std;
int main () {
double a = 0.01;
double b = 45.01 - 45;
double c = b;
std::cout << a-c << std::endl;
return 0;
}
Will give this output:
1.98973e-015
This is because of the way floating points are represented in C++.
One thing you can do is to round the result by using the round() function (c++11 or newer compiler) or by casting the result to an integer with few modifications.
I prefer the casting option because in certain cases using the round() function will need a bit more modification if the result is negative.
double d = int( (a - c) * 100) / 100;
std::cout << d << std::endl;
Will give the following output:
0
Therefore, this will do the trick:
#include <iostream>
using namespace std;
int main () {
double a = 0.01;
double b = 45.01 - 45;
double c = b;
double d = int( (a - c) * 100) / 100;
if (!d) // equivalent to (d == 0)
std::cout << "a is 0.01" << std::endl;
else
std::cout << "a is not 0.01" << std::endl;
return 0;
}
You can read the followings to get a better understanding of the issue -
What Every Computer Scientist Should Know About Floating-Point Arithmetic
Comparing Floating Point Numbers, 2012 Edition
You can also go over the answers in this question from which I have gotten the recommended articles.
Edit:
As Artyer pointed out, this is a way of rounding up the value.
If you use this method you need to replace the '100' int:
double d = int( (a - c) * 100) / 100;
with 10^x
, where x
will be the decimal precision you want to have.