C语言 while 循环嵌套在 while 循环中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16594148/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
while loop nested in a while loop
提问by Yananas
I was using a nested while loop, and ran into a problem, as the inner loop is only run once. To demonstrate I've made a bit of test code.
我正在使用嵌套的 while 循环,但遇到了一个问题,因为内部循环只运行一次。为了演示,我做了一些测试代码。
#include <stdio.h>
int main(){
int i = 0;
int j = 0;
while(i < 10){
printf("i:%d\n", i);
while(j < 10){
printf("j:%d\n", j);
j++;
}
i++;
}
}
This returns:
这将返回:
i:0
j:0
j:1
j:2
j:3
j:4
j:5
j:6
j:7
j:8
j:9
i:1
i:2
i:3
i:4
i:5
i:6
i:7
i:8
i:9
Can anyone explain why the nested loop doesn't execute 10 times? And what can I do to fix it?
谁能解释为什么嵌套循环不执行 10 次?我能做些什么来解决它?
回答by FatalError
You never reset the value of jto 0, and as such, your inner loop condition is never true after the first run. Assigning j = 0;in the outer loop afterward should fix it.
您永远不会重置jto的值,0因此,您的内部循环条件在第一次运行后永远不会为真。j = 0;之后在外循环中分配应该修复它。
回答by FatalError
Because you don't reset it in each iteration of the outer loop. If you want the inner loop to run ten times too, put the initialization of the jvariable inside the outer loop, like this:
因为您不会在外循环的每次迭代中重置它。如果您希望内循环也运行十次,请将j变量的初始化放在外循环中,如下所示:
int i = 0;
while (i < 10) {
printf("i:%d\n", i);
int j = 0;
while (j < 10) {
printf("j:%d\n", j);
j++;
}
i++;
}
回答by alk
You need to re-set the value jto 0after the inner loop is done.
你需要重新设定值j,以0内部循环完成后。
回答by DhruvPathak
jneeds to be initialized to 0 inside the loop.
j需要在循环内初始化为 0。
#include <stdio.h>
int main(){
int i = 0;
int j = 0;
while(i < 10){
printf("i:%d\n", i);
j = 0 ; // initialization
while(j < 10){
printf("j:%d\n", j);
j++;
}
i++;
}
}
回答by Apollo SOFTWARE
You need to reset j to 0. You don't ever do that in your code Make j equal to 0 in your outside loop.
您需要将 j 重置为 0。您永远不会在您的代码中这样做使 j 在您的外部循环中等于 0。
回答by user2387778
The reason your inner loop only executes once is because you initialize j to 0 outside the loop and then never reset it again. After it runs the first time the value of j is 10. It will never be less than 10 again.
您的内部循环只执行一次的原因是因为您在循环外将 j 初始化为 0,然后再也不重置它。第一次运行后,j 的值为 10。它永远不会小于 10。
A better way to do this is to use a forloop:
一个更好的方法是使用for循环:
for (int i = 0; i < 10; i++){
printf("i:%i\n", i);
for (int j = 0; j < 10; j++){
printf("j:%i\n", j);
}
}
It also makes the code look cleaner.
它还使代码看起来更干净。
回答by jjrjrjrj
You never reset the value of j to 0, and as such, your inner loop condition is never true after the first run. Assigning j = 0; in the outer loop afterward should fix it.
您永远不会将 j 的值重置为 0,因此,您的内部循环条件在第一次运行后永远不会为真。赋值 j = 0; 在外循环之后应该修复它。

