来自同一Go程序的不同输出

mas*_*nun 3 go

这是我的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

}
Run Code Online (Sandbox Code Playgroud)

在我的本地机器上,当我运行程序时,我得到525作为输出.当我在Go Playground上运行时,输出为476.

我想知道有什么不同.

pet*_*rSO 5

这是因为特定于实现的大小为int32位或64位.用于int64获得一致的结果.例如,

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

}
Run Code Online (Sandbox Code Playgroud)

输出:

525
Run Code Online (Sandbox Code Playgroud)

游乐场:http://play.golang.org/p/0Cdic16edP


Go编程语言规范

数字类型

 int32       the set of all signed 32-bit integers (-2147483648 to 2147483647)
 int64       the set of all signed 64-bit integers (-9223372036854775808 to 9223372036854775807) 

n位整数的值是n位宽,并使用二进制补码算法表示.

还有一组具有特定于实现的大小的预先声明的数字类型:

 uint     either 32 or 64 bits
 int      same size as uint 

要查看特定于实现的大小int,请运行此程序.

package main

import (
    "fmt"
    "runtime"
    "strconv"
)

func main() {
    fmt.Println(
        "For "+runtime.GOARCH+" the implementation-specific size of int is",
        strconv.IntSize, "bits.",
    )
}
Run Code Online (Sandbox Code Playgroud)

输出:

For amd64 the implementation-specific size of int is 64 bits.

在Go Playground:http://play.golang.org/p/7O6dEdgDNd

For amd64p32 the implementation-specific size of int is 32 bits.