如何在Go中执行除法

120

我正在尝试在Go中执行一个简单的除法操作。

fmt.Println(3/10)

这会打印0而不是0.3,有点奇怪。能否请有人分享一下背后的原因?我想在Go中执行不同的算术运算。

谢谢


阅读The Go Blog: Constants可能会帮助那些第一次面对这个问题的人。 - Marko
1个回答

122
The operands of the binary operation 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 结果。
下面的表达式convertint 变量转换为 float64,以获得 0.3float64 结果:
var i3 = 3
var i10 = 10
fmt.Println(float64(i3) / 10)
fmt.Println(3 / float64(i10))

运行演示操场


我正在输入百分比数据。例如,如果用户输入30,我需要执行30/100 * 某个数字。输入将始终为整数。如何在这种情况下执行除法? - Vrushank Doshi
我尝试了 fmt.Println(float64(3/10)) 但是它给了我0。 - Vrushank Doshi
11
fmt.Println(float64(3) / float64(10)) 的输出结果为 0.3 - peterSO
2
请编辑您的答案,因为3 / 10.0不起作用,正如@robstarbuck的答案所提到的那样。 - Federick Jonathan
注意: fmt.Println(i3 / 10.0) fmt.Println(3.0 / i10)无法正常工作,仍需将其转换为浮点数。 - undefined
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接