dtkp51520 2018-10-31 00:41
浏览 32
已采纳

Go中的实数[重复]

This question already has an answer here:

How to work with real numbers in Go?

For instance:

(627.71/640.26)^(1/30) = 0.999340349 --> correct result

but with Go:

fmt.Print(math.Pow((627.71 / 640.26), (1 / 30))) = 1 --> wrong
</div>
  • 写回答

1条回答 默认 最新

  • doulan8152 2018-10-31 00:45
    关注

    Use floating-point (real), not integer, division. For example,

    package main
    
    import (
        "fmt"
        "math"
    )
    
    func main() {
        fmt.Print(math.Pow((627.71 / 640.26), (1.0 / 30.0)))
    }
    

    Playground: https://play.golang.org/p/o7uVw9doaMu

    Output:

    0.999340348749526
    

    package main
    
    import "fmt"
    
    func main() {
        fmt.Println(1 / 30)     // integer division
        fmt.Println(1.0 / 30.0) // floating-point division
    }
    

    Playground: https://play.golang.org/p/VW9vilCC9M8

    Output:

    0
    0.03333333333333333
    

    The Go Programming Language Specification

    Integer literals

    Floating-point literals

    Arithmetic operators

    Integer operators

    For two integer values x and y, the integer quotient q = x / y and remainder r = x % y satisfy the following relationships:

    x = q*y + r  and  |r| < |y|
    

    with x / y truncated towards zero ("truncated division").

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

报告相同问题?

悬赏问题

  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码