优惠全部云服务器首月 8 折,优惠码 CLOUD去领取

使用相同浮点常量值的不同模式会导致不同的结果

· 阅读约 2 分钟

问题内容

在下面的 go 代码片段中,我很难理解为什么结果不同:

func main() {
    a := -0.2; b := -0.1; 
    fmt.Println(a+b)
    //Outputs expected float value with rounding error  : -0.30000000000000004
    c := (-0.2)+(-0.1)
    fmt.Println(c)
    //Will ouput -0.3 (the actual exact constant).
}

到底发生了什么,当这些常量不用于实例化浮点数时,go 是否以某种方式将 c 操作作为常量而不是 float64 操作执行? 完整工作版本:https://play.golang.org/p/kuicdgfimvf

如有任何见解,我们将不胜感激,谢谢。

解决方案

我尝试使用java,结果是:

public class StringTest {
    public static void main(String[] args) {

        double a = -0.2;
        double b = -0.1;
        System.out.println(a + b);
       //  -0.30000000000000004

        double c = a + b;
        System.out.println(c);
      // -0.30000000000000004

    }
}

似乎任何使用二进制浮点数的编程语言都会有这个问题。某些语言的 number 类型使用 ieee754 标准来表示数字。 而ieee-745 float是什么,可以看到。

以上就是《使用相同浮点常量值的不同模式会导致不同的结果》的详细内容,更多关于的资料请关注公众号!

相关文章

更多「网站和优化」文章服务器使用指南