在 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
}
原文由 pward 发布,翻译遵循 CC BY-SA 4.0 许可协议
您使用 “转换” 类型转换它们
比较值时,您总是希望将较小的类型转换为较大的类型。转换另一种方式可能会截断值:
或者在您的情况下将
maxInt
int64
值转换为int
,您可以使用如果
maxInt
溢出系统上int
类型的最大值,它将无法正确执行。