英文:
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<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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论