GO的fmt.Println((1+8)/2)为什么是4,不是4.5?

fmt.Println("见证奇迹的时刻到了,(1 + 8) / 2 = ", (1+8)/2)
阅读 2.5k
4 个回答

golang 里 untyped contants 的运算结果类型确定方式如下(https://golang.org/ref/spec#C...

Any other operation on untyped constants results in an untyped constant of the same kind; that is, a boolean, integer, floating-point, complex, or string constant. If the untyped operands of a binary operation (other than a shift) are of different kinds, the result is of the operand's kind that appears later in this list: integer, rune, floating-point, complex. For example, an untyped integer constant divided by an untyped complex constant yields an untyped complex constant.

这里大家都是 integer ,所以结果也是 integer.

注意对于有类型的,规则还不太一样(https://golang.org/ref/spec#A...

Arithmetic operators apply to numeric values and yield a result of the same type as the first operand.

PHP这种弱类型才会自动转换类型

强类型都是砍掉小数,不会变浮点数,除非你明确指明

float32(8+1)/2
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题