douji7399 2016-08-03 17:52
浏览 1171
已采纳

如何在Go中将int64转换为int?

In Go, what is the best strategy for converting int64 to int? I am having difficulty comparing the two

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)
    }

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
}
  • 写回答

1条回答 默认 最新

  • drnmslpz42661 2016-08-03 17:55
    关注

    You convert them with a type "conversion"

    var a int
    var b int64
    int64(a) < b
    

    When 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 = 0
    var y int64 = math.MaxInt32 + 1 // y == 2147483648
    if x < int32(y) {
    // this evaluates to false, because int32(y) is -2147483648
    

    Or in your case to convert the maxInt int64 value to an int, you could use

    for 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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题