问题描述
我正在尝试在 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 中执行除法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!