如何在Go中将int64转换为int? [英] How to convert an int64 to int in Go?
问题描述
int64
转换为 int
的最佳策略是什么?我很难比较这两种方法。 package main
import(
math
strings
strconv
)
类型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
$ bfor 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){
//因为int32(y)是-2147483648
,所以计算结果为false
或者在您的情况下,将 maxInt
int64
值转换为 int
,你可以使用
作为:= 2; a< INT(MAXINT); a ++ {
如果 In Go, what is the best strategy for converting on this next line
You convert them with a type "conversion" When comparing values, you always want to convert the smaller type to the larger. Converting the other way will possibly truncate the value: Or in your case to convert the which would fail to execute correctly if 这篇关于如何在Go中将int64转换为int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! maxInt $ c $将无法正确执行c>溢出系统中
int
类型的最大值。 int64
to int
? I am having difficulty comparing the twopackage 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
}
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) {
// this evaluates to false, because int32(y) is -2147483648
maxInt
int64
value to an int
, you could usefor a := 2; a < int(maxInt); a++ {
maxInt
overflows the max value of the int
type on your system.