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

为什么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?

  • 写回答

1条回答 默认 最新

  • 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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?