R 中的嵌套 while 循环行为
我很困惑为什么输出不是我期望的以下嵌套 while 循环中的结果:
i = 1
j = 1
while(i<5){
print("i")
print(i)
i = i + 1
while(j<5){
print("j")
print(j)
j = j + 1
}
}
我得到的输出是:
[1] "i"
[1] 1
[1] "j"
[1] 1
[1] "j"
[1] 2
[1] "j"
[1] 3
[1] "j"
[1] 4
[1] "i"
[1] 2
[1] "i"
[1] 3
[1] "i"
[1] 4
但我期望有
[1] "i"
[1] 1
[1] "j"
[1] 1
[1] "j"
[1] 2
[1] "j"
[1] 3
[1] "j"
[1] 4
[1] "i"
[1] 2
[1] "j"
[1] 1
[1] "j"
[1] 2
[1] "j"
[1] 3
[1] "j"
[1] 4
...
任何建议?感谢您的帮助。
I am puzzled by why the output is not what I expect it to be in the following nested while loops:
i = 1
j = 1
while(i<5){
print("i")
print(i)
i = i + 1
while(j<5){
print("j")
print(j)
j = j + 1
}
}
The output I get is:
[1] "i"
[1] 1
[1] "j"
[1] 1
[1] "j"
[1] 2
[1] "j"
[1] 3
[1] "j"
[1] 4
[1] "i"
[1] 2
[1] "i"
[1] 3
[1] "i"
[1] 4
But I was expecting something along the lines of
[1] "i"
[1] 1
[1] "j"
[1] 1
[1] "j"
[1] 2
[1] "j"
[1] 3
[1] "j"
[1] 4
[1] "i"
[1] 2
[1] "j"
[1] 1
[1] "j"
[1] 2
[1] "j"
[1] 3
[1] "j"
[1] 4
...
Any suggestions? Thank you for your help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将 j 放入循环中,为每个 i 重复所有 j...
Put j inside the loop to repeat all j for each i...
循环的行为没有任何问题。
现在多思考一下您的代码。
您想要的是第二个 while 循环实际上为第一个循环的每个循环循环 4 次。
那么您期望在第一个
while
循环范围内将j
的值设置回 1,神奇吗?您可能想尝试自己做,不是吗?There's nothing wrong about the loop's behavior.
Now think a little bit more about your code.
What you want is your second
while
loop to actually loop 4 times for each loop of the first one.So you're expecting
j
's value to be set back to 1 inside the scope of the firstwhile
loop, magically? You might want to try doing it yourself, don't you?