2018-10-31 00:41

# Go中的实数[重复]

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").

点赞 打赏 评论