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.

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

报告相同问题?

悬赏问题

  • ¥15 为什么我按照电路图做出的仿真和实物都不能使用
  • ¥15 mars2d在vue3中的引入问题
  • ¥50 h5唤醒支付宝并跳转至向小荷包转账界面
  • ¥15 算法题:数的划分,用记忆化DFS做WA求调
  • ¥15 chatglm-6b应用到django项目中,模型加载失败
  • ¥15 CreateBitmapFromWicBitmap内存释放问题。
  • ¥30 win c++ socket
  • ¥15 C# datagridview 栏位进度
  • ¥15 vue3页面el-table页面数据过多
  • ¥100 vue3中融入gRPC-web