本文介绍了如何在Go中将int64转换为int?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 中,将 int64 转换为 int 的最佳策略是什么?我很难比较这两种方法。 package main import(math stringsstrconv) 类型largestPrimeFactor结构{ N int 结果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)} $ b $ b for a:= 2; a< MAXINT; a ++ { if isPrime(a){如果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:= 2; a< MAXINT; a ++ { if(n%a == 0){ flag:= true } } 返回标志} 解决方案您可以使用conversion var a int var b int64 int64(a)< b 比较值时,您总是希望将较小的类型转换为较大的类型。转换另一种方式可能会截断该值: var x int32 = 0 var y int64 = math.MaxInt32 + 1 // y == 2147483648 if x //因为int32(y)是-2147483648 ,所以计算结果为false 或者在您的情况下,将 maxInt int64 值转换为 int ,你可以使用 作为:= 2; a< INT(MAXINT); a ++ { 如果 maxInt 溢出系统中 int 类型的最大值。 In Go, what is the best strategy for converting int64 to int? I am having difficulty comparing the twopackage mainimport ( "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) }on this next line 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} 解决方案 You convert them with a type "conversion"var a intvar b int64int64(a) < bWhen comparing values, you always want to convert the smaller type to the larger. Converting the other way will possibly truncate the value:var x int32 = 0var y int64 = math.MaxInt32 + 1 // y == 2147483648if x < int32(y) {// this evaluates to false, because int32(y) is -2147483648Or in your case to convert the maxInt int64 value to an int, you could usefor a := 2; a < int(maxInt); a++ {which would fail to execute correctly if maxInt overflows the max value of the int type on your system. 这篇关于如何在Go中将int64转换为int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
05-27 14:05