go:整数除以浮点数的问题

    fmt.Println(11 / (10.0 * 1))
    s := []byte("hello world")
    fmt.Println(len(s) / (10.0 * 1))

stdout:
1.1
1

两个的计算结果为什么不一致:都是int/float

阅读 13k
1 个回答

这是因为第一个左侧类型为数值常量,会根据右侧运算值类型float类确定左侧类型,之后再运算,float/float=float,所以是1.1,而第二个len函数返回类型为确定的int,运算会按照左侧类型来执行,右侧被转换为int类型,因此就是int/int=int 值为1

// 如果左侧运算符类型确定,则右侧转为左侧类型再运算
var num1 int = 11
fmt.Println(num1 / 10)
fmt.Println(num1 / 10.0)

// 如果左侧类型不确定,则根据右侧类型推导左侧类型
fmt.Println(11 / 10)
fmt.Println(11 / 10.0)

自动类型转换参考 https://golang.org/ref/spec#C...

A constant value x can be converted to type T in any of these cases:

x is representable by a value of type T.
x is a floating-point constant, T is a floating-point type, and x is representable by a value of type T after rounding using IEEE 754 round-to-even rules, but with an IEEE -0.0 further rounded to an unsigned 0.0. The constant T(x) is the rounded value.
x is an integer constant and T is a string type. The same rule as for non-constant x applies in this case.
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
宣传栏