How to perform division in Go

huangapple go评论84阅读模式
英文:

How to perform division in Go

问题

我正在尝试在Go语言中进行简单的除法运算。

fmt.Println(3/10)

这段代码输出的结果是0,而不是0.3。这有点奇怪。请问有人可以分享一下这背后的原因吗?我还想在Go语言中进行其他算术运算。

谢谢。

英文:

I am trying to perform a simple division in Go.

fmt.Println(3/10)

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.

Thanks

答案1

得分: 121

二元操作 3 / 10 的操作数是未类型化的常量。根据规范 关于带有未类型化常量的二元操作的说明

> 如果二元操作的操作数是不同类型的未类型化常量,操作和(对于非布尔操作)结果使用此列表中后面出现的类型:整数、符文、浮点数、复数。

因为 310 都是未类型化的整数常量,所以表达式的值是未类型化的整数(在这种情况下为 0)。

要获得浮点数常量的结果,其中一个操作数必须是浮点数常量。以下表达式的结果是未类型化的浮点数常量 0.3

3.0 / 10.0
3.0 / 10
3 / 10.0

当除法操作具有未类型化常量操作数和类型化操作数时,类型化操作数决定表达式的类型。确保类型化操作数是 float64,以获得 float64 的结果。

以下表达式将 int 变量转换为 float64,以获得 float64 结果 0.3

var i3 = 3
var i10 = 10
fmt.Println(float64(i3) / 10)
fmt.Println(3 / float64(i10))

运行演示示例

英文:

The operands of the binary operation 3 / 10 are untyped constants. The specification says this about 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

When the division operation has an untyped constant operand and a typed operand, the typed operand determines the type of the expression. Ensure that the typed operand is a float64 to get a float64 result.

The expressions below convert int variables to a float64 to get the float64 result 0.3:

var i3 = 3
var i10 = 10
fmt.Println(float64(i3) / 10)
fmt.Println(3 / float64(i10))

Run a demonstration playground.

huangapple
  • 本文由 发表于 2015年9月28日 11:46:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/32815400.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定