在if条件中使用的II运算符表现奇怪。

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

II operator in if condition works strange

问题

我在练习Go语言时遇到了一个问题。我想要计算小于10且能被5或3整除的所有数字的和。但是当我运行以下代码时出现了问题:

sum := 0
for j := 0; j < 10; j++ {
   if (j%5 == 0) || (j%3 == 0) {
      fmt.Println(j)
      sum += j
   }
}

结果输出为:

0
1
2
3
4
5
6
7
8
9
45

奇怪的是,如果我只检查能否被3整除或者只检查能否被5整除,代码就能正常工作。

英文:

I'm totally new in terms of go and for practice I decided to write a few simple apps. Quite fast I got into weird problem:

sum := 0
for j:= 0; j&lt;10; j++ {
   if (j%5 == 0) || (i%3 == 0) {
      fmt.Println(j)
      sum += j
   }
}

Obviously I want to sum up all the numbers divisible by 5 or by 3 lower than 10. But when I run it I get:

0
1
2
3
4
5
6
7
8
9
45

The weird part is it works fine if I check for divisibility only by 3 or only by 5...

答案1

得分: 1

我不知道i变量是如何定义的,但是将它改为j后,它按预期工作了。请查看这个Go Playground示例

英文:

I don't how know how is defined the i variable but change it to j it works as expected, take a look on this go playground example

答案2

得分: 0

在if语句中使用||代替|

||是“逻辑或”运算符,这是你想要的。

一旦你解决了这个问题,还要将变量i改为j,因为这是你想要进行比较的变量。

英文:

Use || instead of | in the if statement.

||
is "logical or" which is what you want.

Once you have fixed that issue, also change the "i" variable to "j" because that's what you want to compare against.

huangapple
  • 本文由 发表于 2016年10月28日 20:27:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/40305117.html
匿名

发表评论

匿名网友

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

确定