douningchang3610
douningchang3610
2019-02-07 05:41
浏览 64
已采纳

为什么fmt.Println(float64(1/2))显示为0?

package main

import (
    "fmt"
)

func main() {
    fmt.Println(float64(1/2))
}

Why it prints: 0

Playground link: https://play.golang.org/p/KGgao6n8lTA

Is it because fmt.Println precision is low?

图片转代码服务由CSDN问答提供 功能建议

 包main 
 
import(
“ fmt” 
)
 
func main(  ){
 fmt.Println(float64(1/2))
} 
   
 
 

为什么打印:0

游乐场链接: https://play.golang.org/p/KGgao6n8lTA

是因为 fmt.Println 的精度低吗?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongxie7683
    dongxie7683 2019-02-07 05:44
    已采纳

    The order of operations here is: 1/2 = 0 (integer division truncates decimal places) followed by float64(0) = 0, then fmt.Println(0).

    So in short: the integer division is truncated to 0. Everything else works fine.

    As @Amadan commented, you can force a floating point division by casting one of the integers, i.e. float64(1) / 2 = 0.5.

    点赞 评论

相关推荐