减去两个十进制数给出奇怪的输出 [英] Subtracting two decimal numbers giving weird outputs
问题描述
public static void main(String args []){
System.out.println(2.00 - 1.10);
$ / code>
输出是
0.8999999999999999
当我尝试将代码更改为
2.00d - 1.10d
仍然得到与 0.8999999999999999
对于 2.00d - 1.10f
输出是 0.8999999761581421
对于, 2.00f - 1.10d
输出是 0.8999999999999999
对于 2.00f - 1.10f
输出是 0.9
为什么不把输出作为 0.9
放在首位呢?我无法做出任何正面或反面的意见?有人可以说清楚这一点吗?
在二进制0.1是0.00011001100110011001100110011001 .....,
因此,它不能完全用二进制表示。取决于你在哪里取整(float或double),你会得到不同的答案。
所以0.1f = 0.000110011001100110011001100
和0.1d = 0.0001100110011001100110011001100110011001100110011001
您注意到该数字在1100周期内重复。然而浮点数和双精度在循环中的不同点上分开。就这样,一个错误上来,另一个下来;导致差异。
但最重要的是,
永远不要假设浮点数是准确的
While I was having fun with codes from Java Puzzlers(I don't have the book) I came across this piece of code
public static void main(String args[]) {
System.out.println(2.00 - 1.10);
}
Output is
0.8999999999999999
When I tried changing the code to
2.00d - 1.10d
still I get the same output as 0.8999999999999999
For,2.00d - 1.10f
Output is 0.8999999761581421
For,2.00f - 1.10d
Output is 0.8999999999999999
For,2.00f - 1.10f
Output is 0.9
Why din't I get the output as 0.9
in the first place? I could not make any heads or tails out of this? Can somebody articulate this?
In binary 0.1 is 0.00011001100110011001100110011001.....,
As such it cannot be represented exactly in binary. Depending where you round off (float or double) you get different answers.
So 0.1f =0.000110011001100110011001100 And 0.1d=0.0001100110011001100110011001100110011001100110011001
You note that the number repeats on a 1100 cycle. However the float and double precision split it at a different point in the cycle. As such on one the error rounds up and the other rounds down; leading to the difference.
But most importantly; Never assume floating point numbers are exact
这篇关于减去两个十进制数给出奇怪的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!