英文:
Golang overflows int64
问题
我尝试使用这段代码,但是出现了一个错误:常量100000000000000000000000超出了int64的范围。
你应该如何修复这个问题?
// 用较小的数字初始化大数
count, one := big.NewInt(100000000000000000000000), big.NewInt(1)
英文:
I try to use this code, but gives me an error: constant 100000000000000000000000 overflows int64
How can I fix that ?
// Initialise big numbers with small numbers
count, one := big.NewInt(100000000000000000000000), big.NewInt(1)
答案1
得分: 9
例如这样:
package main
import (
"fmt"
"math/big"
)
func main() {
count, one := new(big.Int), big.NewInt(1)
count.SetString("100000000000000000000000", 10)
fmt.Println(count)
}
链接:
http://play.golang.org/p/eEXooVOs9Z
英文:
for example so:
count,one := new(big.Int), big.NewInt(1)
count.SetString("100000000000000000000000",10)
答案2
得分: 2
这段代码中的问题在于,big.NewInt实际上是在分配一个int64类型的整数。你想要分配的数字需要超过64位才能存在,所以分配失败了。
然而,使用big包的方式,如果你想要相加的两个大数都在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是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
英文:
It won't work because under the hood, big.NewInt is actually allocating an int64. The number that you want to allocate into a big.NewInt would need more than 64bits to exist, so it failed.
However, with how big works, if you wanted to add two large numbers below MaxInt64, you can do that! Even if the sum is greater than MaxInt64. Here is an example I just wrote up (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 );
}
Which results in:
count: 10000000000000000000
max int64: 9223372036854775807
Now, if you're still curious about how NewInt works under the hood, here is the function you're using, taken from Go's documentation,:
// NewInt allocates and returns a new Int set to x.
func NewInt(x int64) *Int {
return new(Int).SetInt64(x)
}
Sources:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论