#include <iostream>
using namespace Std;
int main ()
{
float sum=0.0;
for (int i=0;i<10;i++)
{
sum=sum+0.01;
}
cout<<sum<<endl;
if (sum==0.1)
{
cout<< "Equal" <<endl;
}
Else
{
cout<< "Unequal" <<endl;
}
return 0;
}
/*
Summary:
1) Running results
0.1
Not equal
2) explanation
Through analysis, the expression sum==0.1, while mathematically true, is not true in the program.
The reason is that the finite precision of a floating-point type causes rounding errors to be introduced in a repeating accumulation operation, so
The results in the program are not equal
3) Resolve:
In general, when checking whether two floating-point numbers are equal, the maximum error tolerance can be specified to check
Whether the two values are close enough, rather than directly testing whether they are equal or unequal, for example, you can
Specify the maximum error tolerance in advance:
const float DELTA=0.00001, then change sum=0.1 to: Fabs (sum-0.1) <=delta
, which uses the math library function fabs () to return the absolute value of a floating-point parameter
*/
The correct way to compare the code is as follows://////////////////////////////////
#include <iostream>
#include <math.h>
using namespace Std;
int main ()
{
float sum=0.0;
const float DELTA=0.00001;
for (int i=0;i<10;i++)
{
sum=sum+0.01;
}
cout<<sum<<endl;
if (Fabs (sum-0.1) <=delta)
{
cout<< "Equal" <<endl;
}
Else
{
cout<< "Unequal" <<endl;
}
return 0;
}
You need to display a number correctly on the monitor, but this number has a lot of spam, and the 0 and double-precision data behind the floating-point data is not what I want, of course, who cares about 0.000000001 points, so it's necessary to take a break for our decimal team.
For example we have 12.3 Yuan 5 points, no, we should follow the banker (of course reminds me of the banker algorithm, a borrowing rule) to calculate the cost plus interest, altogether is 100000200.2300222 yuan. The problem is that the monitor doesn't give a force. Had to reluctantly reserved two digits after the decimal point. But unfortunately we chose a very sad number, if the number above is multiplied by 100, then the cast type is an unsigned integer (can I have a signed integer type?). Of course, the savings users just do not want the check overdraft), has been overflow, bad, the user said one of my million is missing.
If there is no such huge number (of course, a small ordinary family, at most four or five zeros, but he is Bill), multiplied by 100, and then cast the type to remove the rotten egg after the decimal point, and then format the output, of course, is to find the model.
Just because unsigned integers can represent a maximum range of 4000000000, or 4 billion, we need to provide the highest national treatment, the alternative way to deal with it (sleep first, sleepy afternoon)
How to display and compare floating point numbers correctly