在Go语言中,将
int64
转换为int
的最佳策略是什么?我很难比较这两种类型。package main
import (
"math"
"strings"
"strconv"
)
type largestPrimeFactor struct {
N int
Result int
}
func main() {
base := largestPrimeFactor{N:13195}
max := math.Sqrt(float64(base.N))
maxStr := strconv.FormatFloat(max, 'E', 'G', 64)
maxShift := strings.Split(maxStr, ".")[0]
maxInt, err := strconv.ParseInt(maxShift, 10, 64)
if (err != nil) {
panic(err)
}
在下一行上
for a := 2; a < maxInt; a++ {
if isPrime(a) {
if base.N % a == 0 {
base.Result = a
}
}
}
println(base)
}
func isPrime(n int) bool {
flag := false
max := math.Sqrt(float64(n))
maxStr := strconv.FormatFloat(max, 'E', 'G', 64)
maxShift := strings.Split(maxStr, ".")[0]
maxInt, err := strconv.ParseInt(maxShift, 10, 64)
if (err != nil) {
panic(err)
}
for a := 2; a < maxInt; a++ {
if (n % a == 0) {
flag := true
}
}
return flag
}
0.1 * 0.2 == 0.020000000000000004
一样,您应该了解整数类型的工作原理。您在这里遇到了X Y问题 - 您想让代码工作,但您要求的解决方案是不正确的解决方案。 - JimBint64
比int
更大是正确的? - cevingint64
比int
更大或者相等,因此从int
转换为int64
将永远不会丢失数据,而反向情况则不成立。 - JimB