计算时结果与书上的不一致
……
double a=18.4;
double b=a%4;
……
运行结果
b= 2.3999999999999986
(13个9)而书上给的结果是
b=2.4
请问这是怎么回事?是书上错了吗?
A floating point number(float,double), the calculation of them is SELDOM exact.
A simple example would be a float variable, a float variable is a 32-bit signed variable that contains 3 parts:
a sign-bit which is used to represent the sign of the number: 0 (positive), 1 (nagetive)
a 8 bit exponent field, this decides the range of the variable, a exponent is represented as unsigned(sign and maginitude) and use a bias of 127. 1000 0001 will be actually 8*16 + 1 = 129 - 127 = 2, so the actual expoent is 2^2;
a 23-bit sigificand, which decides the presesion of the variable, this is the main part of your question, the calculation is seldom exact because the field to represent the "precision" is limited, and it is not possible to represent it exactly as what it is, so flaoting number calculation always round value to give a NOT exact , but exact enough in the sense how we need them.
I know I have made you very confused now, just remember, floating number Arithematic is seldom exact. Since the way they are built up are "complicated" as i described above.
an example of floating point number;
float f = - 3.5;
//look at the actual bits
- 3.5 = 1100 0000 0110 0000 0000 0000 0000 0000 (0xC0600000)