dongxu7121 2018-01-09 00:03
浏览 31
已采纳

已声明且未在循环中使用的变量

Got confusion with a function

package main

import "fmt"

func dominantIndex(nums []int) int {
    var max, max2 = -12423421, -12423421
    var i, j = -1, -1
    for k, num := range nums {
        if num > max {
            max, max2 = num, max
            i, j = k, i
        } else if num > max2 {
            max2 = num
            j = k
        }
    }
    if max >= max2*2 {
        return i
    }
    return -1
}


func main() {
    var a = []int{3, 6, 100, 1, 0 }
    fmt.Print(dominantIndex(a))
}

I have to insert a nonsense statement in the loop such as j = j. Otherwise, it raises ./hello.go:7:6: j declared and not used. Wonder if there is any fix.

  • 写回答

1条回答 默认 最新

  • dongzhuner6981 2018-01-09 00:07
    关注

    You assign a value to j, but you don't use j. That is the problem. You could as well leave j out, without changing the functionality of the code.

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

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题