我正在尝试在Go中执行一个简单的除法操作。
fmt.Println(3/10)
这会打印0而不是0.3,有点奇怪。能否请有人分享一下背后的原因?我想在Go中执行不同的算术运算。
谢谢
我正在尝试在Go中执行一个简单的除法操作。
fmt.Println(3/10)
这会打印0而不是0.3,有点奇怪。能否请有人分享一下背后的原因?我想在Go中执行不同的算术运算。
谢谢
3 / 10
are untyped constants. According to the specification binary operations with untyped constants, if the operands of a binary operation are different kinds of untyped constants, the operation and, for non-boolean operations, the result use the kind that appears later in this list: integer, rune, floating-point, complex. Because 3
and 10
are untyped integer constants, the value of the expression is an untyped integer (0
in this case). To get a floating-point constant result, one of the operands must be a floating-point constant. The following expressions evaluate to the untyped floating-point constant 0.3
:3.0 / 10.0
3.0 / 10
3 / 10.0
float64
以获得 float64
结果。int
变量转换为 float64
,以获得 0.3
的 float64
结果:var i3 = 3
var i10 = 10
fmt.Println(float64(i3) / 10)
fmt.Println(3 / float64(i10))
fmt.Println(float64(3) / float64(10))
的输出结果为 0.3
。 - peterSO3 / 10.0
不起作用,正如@robstarbuck的答案所提到的那样。 - Federick Jonathanfmt.Println(i3 / 10.0)
fmt.Println(3.0 / i10)
无法正常工作,仍需将其转换为浮点数。 - undefined