[英]Different output from the same Go program
Here is my Go code: http://play.golang.org/p/CDUagFZ-rk 这是我的Go代码: http : //play.golang.org/p/CDUagFZ-rk
package main
import "fmt"
func main() {
var max int = 0
for i := 0; i < 1000000; i++ {
var len int = GetCollatzSeqLen(i)
if len > max {
max = len
}
}
fmt.Println(max)
}
func GetCollatzSeqLen(n int) int {
var len int = 1
for n > 1 {
len++
if n%2 == 0 {
n = n / 2
} else {
n = 3*n + 1
}
}
return len
}
On my local machine, when I run the program, I get 525 as the output. 在我的本地机器上,当我运行程序时,我得到525作为输出。 When I run it on the Go Playground, the output is 476. 当我在Go Playground上运行时,输出为476。
I am wondering what's different. 我想知道有什么不同。
It's because of the implementation-specific size of int
, 32 or 64 bits. 这是因为int
的实现特定大小,32位或64位。 Use int64
for consistent results. 使用int64
获得一致的结果。 For example, 例如,
package main
import "fmt"
func main() {
var max int64 = 0
for i := int64(0); i < 1000000; i++ {
var len int64 = GetCollatzSeqLen(i)
if len > max {
max = len
}
}
fmt.Println(max)
}
func GetCollatzSeqLen(n int64) int64 {
var len int64 = 1
for n > 1 {
len++
if n%2 == 0 {
n = n / 2
} else {
n = 3*n + 1
}
}
return len
}
Output: 输出:
525
Playground: http://play.golang.org/p/0Cdic16edP 游乐场: http : //play.golang.org/p/0Cdic16edP
The Go Programming Language Specification Go编程语言规范
\n int32 the set of all signed 32-bit integers (-2147483648 to 2147483647) int32所有带符号的32位整数的集合(-2147483648到2147483647)\n int64 the set of all signed 64-bit integers (-9223372036854775808 to 9223372036854775807) int64所有带符号的64位整数的集合(-9223372036854775808到9223372036854775807)The value of an n-bit integer is n bits wide and represented using two's complement arithmetic. n位整数的值是n位宽,并使用二进制补码算法表示。
There is also a set of predeclared numeric types with implementation-specific sizes: 还有一组具有特定于实现的大小的预先声明的数字类型:
\n uint either 32 or 64 bits uint 32或64位\n int same size as uint 与uint相同的大小
To see the implementation-specific size of int
, run this program. 要查看特定于实现的int
大小,请运行此程序。
package main
import (
"fmt"
"runtime"
"strconv"
)
func main() {
fmt.Println(
"For "+runtime.GOARCH+" the implementation-specific size of int is",
strconv.IntSize, "bits.",
)
}
Output: 输出:
For amd64 the implementation-specific size of int is 64 bits.
On Go Playground: http://play.golang.org/p/7O6dEdgDNd 在Go Playground: http : //play.golang.org/p/7O6dEdgDNd
For amd64p32 the implementation-specific size of int is 32 bits.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.