2015-06-14 55 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