同一Go程序的不同输出
这是我的密码:同一Go程序的不同输出,go,Go,这是我的密码: 主程序包 输入“fmt” func main(){ var max int=0 对于i:=0;imax{ 最大值=len } } fmt.Println(最大值) } 函数GetCollatzSeqLen(n int)int{ 变量len int=1 对于n>1{ 莱恩++ 如果n%2==0{ n=n/2 }否则{ n=3*n+1 } } 回程透镜 } 在我的本地机器上,当我运行程序时,我得到525作为输出。当我在运动场上运行它时,输出是476 我想知道有什么不同 这是因为in
主程序包
输入“fmt”
func main(){
var max int=0
对于i:=0;i<1000000;i++{
var len int=GetCollatzSeqLen(一)
如果len>max{
最大值=len
}
}
fmt.Println(最大值)
}
函数GetCollatzSeqLen(n int)int{
变量len int=1
对于n>1{
莱恩++
如果n%2==0{
n=n/2
}否则{
n=3*n+1
}
}
回程透镜
}
在我的本地机器上,当我运行程序时,我得到525作为输出。当我在运动场上运行它时,输出是476
我想知道有什么不同 这是因为
int
、32或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
}
游乐场:
输出:
525
For amd64 the implementation-specific size of int is 64 bits.
对于amd64,int的实现特定大小为64位。
运动场:
对于amd64p32,int的实现特定大小为32位。
如果你玩得足够多,你可以打一个n甚至超过2^64的数字。可以处理这样的数字,但代价是计算速度较慢,代码更冗长。 int32 the set of all signed 32-bit integers (-2147483648 to 2147483647) int64 the set of all signed 64-bit integers (-9223372036854775808 to 9223372036854775807) uint either 32 or 64 bits int same size as uint
package main
import (
"fmt"
"runtime"
"strconv"
)
func main() {
fmt.Println(
"For "+runtime.GOARCH+" the implementation-specific size of int is",
strconv.IntSize, "bits.",
)
}
For amd64 the implementation-specific size of int is 64 bits.
For amd64p32 the implementation-specific size of int is 32 bits.