问题描述
我正在尝试在Go中执行简单的划分.
I am trying to perform a simple division in Go.
fmt.Println(3/10)
这将打印0而不是0.3.这有点奇怪.有人可以分享这背后的原因吗?我想在Go中执行不同的算术运算.
This prints 0 instead of 0.3. This is kind of weird. Could someone please share what is the reason behind this? i want to perform different arithmetic operations in Go.
谢谢
推荐答案
表达式3 / 10
是无类型的常量表达式.规范对常量表达式进行了说明
The expression 3 / 10
is an untyped constant expression. The specification says this about constant expressions
因为3
和10
是无类型整数常量,所以表达式的值是无类型整数(在这种情况下为0
).
Because 3
and 10
are untyped integer constants, the value of the expression is an untyped integer (0
in this case).
其中一个操作数必须是浮点常量,结果必须是浮点常量.以下表达式对无类型浮点常量0.3
求值:
One of the operands must be a floating-point constant for the result to 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
常量0.3
:
It's also possible to use typed constants. The following expressions evaluate to the float64
constant 0.3
:
float64(3) / float64(10)
float64(3) / 10
3 / float64(10)
打印以上任何表达式将打印0.3
.例如,fmt.Println(3.0 / 10)
打印0.3
.
Printing any of the above expressions will print 0.3
. For example, fmt.Println(3.0 / 10)
prints 0.3
.
这篇关于如何在Go中执行除法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!