R 中的嵌套 while 循环行为

发布于 2024-09-18 14:34:00 字数 543 浏览 3 评论 0原文

我很困惑为什么输出不是我期望的以下嵌套 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

三生池水覆流年 2024-09-25 14:34:01

将 j 放入循环中,为每个 i 重复所有 j...

    i = 1
while(i<5){
 print("i")
 print(i)
 i = i + 1
    j = 1
    while(j<5){
    print("j")
    print(j)
    j = j + 1
    }
 }

Put j inside the loop to repeat all j for each i...

    i = 1
while(i<5){
 print("i")
 print(i)
 i = i + 1
    j = 1
    while(j<5){
    print("j")
    print(j)
    j = j + 1
    }
 }
欲拥i 2024-09-25 14:34:00

循环的行为没有任何问题。

i = 1 // Beginning of your code, you're initializing i, changing its value to 1
j = 1 // ... initializing j as well.
while(i<5){   // looping while i < 5
 print("i")
 print(i)
 i = i + 1    // incrementing i
 while(j<5){  // looping while j is < 5
  print("j")
  print(j)
  j = j + 1   // incrementing j
 }
}

现在多思考一下您的代码。

您想要的是第二个 while 循环实际上为第一个循环的每个循环循环 4 次。

那么您期望在第一个 while 循环范围内将 j 的值设置回 1,神奇吗?您可能想尝试自己做,不是吗?

There's nothing wrong about the loop's behavior.

i = 1 // Beginning of your code, you're initializing i, changing its value to 1
j = 1 // ... initializing j as well.
while(i<5){   // looping while i < 5
 print("i")
 print(i)
 i = i + 1    // incrementing i
 while(j<5){  // looping while j is < 5
  print("j")
  print(j)
  j = j + 1   // incrementing j
 }
}

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 first while loop, magically? You might want to try doing it yourself, don't you?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文