已评估但未使用

huangapple go评论88阅读模式
英文:

Evaluated but not used

问题

我不确定这里发生了什么。

我正在处理欧拉计划第8题,编写了以下函数来处理获取5个数字的乘积:

func fiveDigitProduct(n int) int {
    localMax := n + 5
    product := 1
    for n; n < localMax; n++ {
        f, _ := strconv.Atoi(input[n])
        product *= f
    }
    return product
}

然而,我一直收到警告信息“n evaluated but not used”。我不知道为什么会发生这种情况。

英文:

I'm not sure what's happening here.

I'm working on Project Euler #8 and have come up with the following function to handle getting the product of 5 digits:

func fiveDigitProduct(n int) int {
	localMax := n + 5
	product := 1
	for n; n &lt; localMax; n++ {
		f, _ := strconv.Atoi(input[n])
		product *= f
	}
	return product
}

However, I keep getting the warning "n evaluated but not used". I have no idea why this is happening.

答案1

得分: 2

你的For语句InitStmt(初始化语句)实际上没有进行任何初始化。你要求编译器评估n,但没有对其进行任何操作,这就是编译器抱怨的原因。由于你不需要为循环初始化n,只需这样做:

for ; n < localMax; n++ {
英文:

The InitStmt (initialization statement) of your For Statement isn't actually doing any initialization. You're asking the compiler to evaluate n but not do anything with it, which is what the compiler is complaining about. Since you don't need to initialize n for you loop, just do:

for ; n &lt; localMax; n++ {

答案2

得分: 0

for循环的初始化部分和后置部分(其中你增加n的部分)需要是一个简单语句(只有“n”不是一个语句,它将是一个表达式,所以你尝试的语法是不正确的)。如果你将初始化部分设为n = n或n := n(在for循环的作用域内进行新的变量声明),它将是一个有效的语句并且可以工作。如上面的帖子所建议的,由于你不打算在初始化部分做任何事情,最好将其省略掉。

英文:

The initialization part of a for loop as also the post part (where you increment n) needs to be a simple statement (and just "n" is not a statement, it'll be an expression, so what you are trying to do is syntactically incorrect). If you make the init part n = n or n := n (a new variable declaration within the scope of the for loop), it'll be a valid statement and will work. As suggested in the above posts, since you don't intend to do anything in the init part it's best to leave it out.

huangapple
  • 本文由 发表于 2017年6月29日 09:29:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/44814963.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定