2015-06-14 218 views
4

我嘗試使用此代碼,但給我一個錯誤:常量100000000000000000000000溢出int64Golang溢出int64

我該如何解決這個問題?

// Initialise big numbers with small numbers 
count, one := big.NewInt(100000000000000000000000), big.NewInt(1) 

回答

2

它不會因爲引擎蓋下工作,big.NewInt實際上是分配一個Int64。你想分配給big.NewInt的數字需要多於64位才能存在,所以它失敗了。

但是,如果您想在MaxInt64下面添加兩個大數字,那麼您可以做到這一點!即使總和大於MaxInt64。下面是一個例子,我只是寫了(http://play.golang.org/p/Jv52bMLP_B):

func main() { 
    count := big.NewInt(0); 

    count.Add(count, big.NewInt(5000000000000000000)); 
    count.Add(count, big.NewInt(5000000000000000000)); 

    //9223372036854775807 is the max value represented by int64: 2^63 - 1 
    fmt.Printf("count:  %v\nmax int64: 9223372036854775807\n", count); 
} 

,這導致:

count:  10000000000000000000 
max int64: 9223372036854775807 

現在,如果你還是好奇NewInt引擎蓋下是如何工作的,這裏是功能您正在使用,從Go的資料爲準,:

// NewInt allocates and returns a new Int set to x. 
func NewInt(x int64) *Int { 
    return new(Int).SetInt64(x) 
} 

來源:

https://golang.org/pkg/math/big/#NewInt

https://golang.org/src/math/big/int.go?s=1058:1083#L51