如何在Go中执行除法 [英] How to perform division in Go

查看:389
本文介绍了如何在Go中执行除法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在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

如果二进制运算的操作数是不同类型的无类型常量,则该运算以及对于非布尔运算而言,结果将使用此列表后面显示的类型:整数,符文,浮点数和复数. /p>

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.

因为310是无类型整数常量,所以表达式的值是无类型整数(在这种情况下为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中执行除法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆