Hi,
Floating point values are not represented exactly - they use binary fractions.
Btw, double is the default because the precision of float is easily exceeded, it can only do 6 or 7 significant figures. double can do 15 or 16 :+) Only use float if some library requires it, typically a graphics library.
A simple way to solve this is to use
std::setprecision. The default for
std::cout is 6sf, so in this case if you set something less than that it will print zero with the number dp you specify. But that will not fly if you want more than 6, or need a definitive result for things like check for divide by zero, or equality.
One can use a precision value and relational tests to get the desired result:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
#include <iostream>
//using namespace std; // <-- avoid this, Google why
#include <iomanip>
#include <cmath>
int main()
{
const double precision = 0.001;
const double value1 = 0.1;
double value2 = 1.0 - (10.0 * value1);
if(std::abs(value2) < precision ) {
std::cout << "Value is zero - (less than " << precision << ")\n";
}
else {
std::cout << "Value is not zero - (greater than " << precision << ")\n";
}
return 0;
}
|
Can do something similar for equality - absolute value of the difference between the 2 numbers. Should write functions that return a bool type to do this.
Of course one wouldn't normally print out values like that, use the bool functions in tests to check for equality or zero.
Good Luck !!