gpt4 book ai didi

java - 了解 float 计数器

转载 作者:行者123 更新时间:2023-11-29 10:05:25 24 4
gpt4 key购买 nike

我有以下简单代码:

for (float i=0; i<1f; i+=0.1) {
System.out.println(i);
}

我刚刚得到以下结果:

0.0
0.1
0.2
0.3
0.4
0.5
0.6
0.70000005
0.8000001
0.9000001

但我不明白为什么会有。拜托,我希望你能告诉我。谢谢。

最佳答案

来自 The Floating-Point Guide :

Why don’t my numbers, like 0.1 + 0.2 add up to a nice round 0.3, and instead I get a weird result like 0.30000000000000004?

Because internally, computers use a format (binary floating-point) that cannot accurately represent a number like 0.1, 0.2 or 0.3 at all.

When the code is compiled or interpreted, your “0.1” is already rounded to the nearest number in that format, which results in a small rounding error even before the calculation happens.

关于java - 了解 float 计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9686637/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com