douti8321 2014-07-26 17:29 采纳率: 0%
浏览 268
已采纳

如何在Go中的if语句中更新变量的值?

I'm trying to learn Go and I've created a function where I declare a variable game_ratio and set it to 0.0. I then have an if statement where I try and update the value of game_ratio. When I try and compile, I get the following error message: 'game_ratio declared and not used'

Here's my function:

func gameRatio(score1 int, score2 int, max_score float64) float64 {
    var game_ratio float64 = 0.0
    var scaled_score_1 = scaleScore(score1, max_score)
    var scaled_score_2 = scaleScore(score2, max_score)
    fmt.Printf("Scaled score for %v is %v
", score1, scaled_score_1)
    fmt.Printf("Scaled score for %v is %v
", score2, scaled_score_2)
    if score1 > score2 {
        game_ratio := (scaled_score_1+1.0)/(scaled_score_1+scaled_score_2+2.0) + 1.0*0.5
    }
    return game_ratio
}

Here's the code to call it:

func main() {
    flag.Parse()
    s1 := flag.Arg(0)
    s2 := flag.Arg(1)
    i1, err := strconv.Atoi(s1)
    i2, err := strconv.Atoi(s2)
    if err != nil {
        fmt.Println(err)
        os.Exit(2)
    }
    fmt.Println("Game ratio is", gameRatio(i1, i2, 6))
}

ScaleScore is another function I have written. If I remove the if statement, the code works.

To run my app, I type 'rankings 28 24'

  • 写回答

1条回答 默认 最新

  • douhoulei4706 2014-07-26 17:37
    关注

    The short variable declaration is redeclaring game_ratio.

    game_ratio := (scaled_score_1+1.0)/(scaled_score_1+scaled_score_2+2.0) + 1.0*0.5
    

    Use an assignment. Write:

    game_ratio = (scaled_score_1+1.0)/(scaled_score_1+scaled_score_2+2.0) + 1.0*0.5
    

    The Go Programming Language Specification

    Short variable declarations

    A short variable declaration uses the syntax:

    ShortVarDecl = IdentifierList ":=" ExpressionList .
    

    It is shorthand for a regular variable declaration with initializer expressions but no types:

    "var" IdentifierList = ExpressionList .
    

    Unlike regular variable declarations, a short variable declaration may redeclare variables provided they were originally declared earlier in the same block with the same type, and at least one of the non-blank variables is new. As a consequence, redeclaration can only appear in a multi-variable short declaration. Redeclaration does not introduce a new variable; it just assigns a new value to the original.

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

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题