计算时结果与书上的不一致
……
double a=18.4;
double b=a%4;
……
运行结果
b= 2.3999999999999986
(13个9)而书上给的结果是
b=2.4
请问这是怎么回事?是书上错了吗?
----------------解决方案--------------------------------------------------------
这个应该是浮点数的精度问题。浮点数是不精确的。若要精确计算,建议你使用BigDecimal,它的精度是最高的
BigDecimal a = new BigDecimal(18.4);
BigDecimal b = a.divide(a,2,2);
结果:2.40
如果你需要3位小数,则改为:
BigDecimal b = a.divide(a,3,2);
----------------解决方案--------------------------------------------------------
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)
----------------解决方案--------------------------------------------------------