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

如何在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 如何构建全国统一的物流管理平台?
  • ¥100 ijkplayer使用AndroidStudio/CMake编译,如何支持 rtsp 直播流?
  • ¥20 和学习数据的传参方式,选择正确的传参方式有关
  • ¥15 这是网络安全里面的poem code
  • ¥15 用js遍历数据并对非空元素添加css样式
  • ¥15 使用autodl云训练,希望有直接运行的代码(关键词-数据集)
  • ¥50 python写segy数据出错
  • ¥20 关于线性结构的问题:希望能从头到尾完整地帮我改一下,困扰我很久了
  • ¥30 3D多模态医疗数据集-视觉问答
  • ¥20 设计一个二极管稳压值检测电路