自
912 * 0.01
是一个常量表达式,它被精确地评估。因此,写 fmt.Println(912 * 0.01)
与写 fmt.Println(9.12)
的效果相同。当你将 912
固定为 float64
时,浮点乘法的另一个操作数被隐式固定为 float64
。因此,表达式 float64(912)* 0.01
表现得像 float64(912)* float64(0.01)
。 0.01在 float64
中不能精确表示,因此在表达式 float64(912 * 0.01)
,它出现在第一个例子中 fmt.Println()
的参数中,解释了不同的结果。
Consider these two cases:
fmt.Println(912 * 0.01)
fmt.Println(float64(912) * 0.01)
The second one prints 9.120000000000001, which is actually fine, I understand why that is happening.
However, why does the first line print 9.12, without the …01 at the end? Does Go multiply the two untyped constants and simply replace them with a 9.12 literal when compiling?
As per spec:
Since
912 * 0.01
is a constant expression, it is evaluated exactly. Thus, writing fmt.Println(912 * 0.01)
has the same effect as writing fmt.Println(9.12)
. When you pin 912
to float64
, the other operand of the floating-point multiplication is implicitly pinned to float64
, too. Thus, the expression float64(912) * 0.01
behaves like float64(912) * float64(0.01)
. 0.01 is not exactly representable in a float64
, thus precision is lost in a different place than in the expression float64(912 * 0.01)
which arises in the argument of fmt.Println()
in your first example, explaining the different results.
这篇关于为什么这两个float64有不同的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!