在下面的 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
}
}
似乎任何使用二进制浮点数的编程语言都会有这个问题。某些语言的数字类型IEEE754用于表示数字的标准。 什么是IEEE-745浮子,你可以看到它。