dsgw8802 2019-08-13 09:54
浏览 145

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

This question already has an answer here:

in the following snippet of go code I struggle to understand why the results are different:

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).
}

What is happening exactly, does go somehow performs the c operation as constant instead of float64 operation when these constants are not used to instantiate floats? Full working version : https://play.golang.org/p/kUICDGFiMvf

Any insights would be appreciated, thanks.

</div>
  • 写回答

1条回答 默认 最新

  • dongpang4470 2019-08-13 12:36
    关注

    i try to use java and the resule is

    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
    
        }
    }
    

    it seems that the any programming language that uses binary floating point numbers will have this problem. some language's Number type used IEEE754 standard to represent number. And what is IEEE-745 float ,you can see it.

    评论

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料