在下面的代码中,我可以跟踪每个for循环迭代的次数,如果我单独查看它们。例如,两个for循环迭代10次,但是当你把它们放在一起时,字符串“hi”会打印超过20次。
内循环迭代了多少次?
for(int j=0; j<10; j++)
for(int k=10; k>0; k--)
System.out.println("hi");
答案 0 :(得分:3)
就像将每个迭代次数相乘(在这种情况下为10 * 10)一样简单。如果您发现它并不像这样简单,您可以执行以下测试:
int count = 0;
for(int j=0; j<10; j++){
for(int k=10; k>0; k--){
count++;
}
}
System.out.println("The nested loop iterated " + String.valueOf(count) + " times!");
编辑:或许更容易理解正在发生的事情:
int total_count = 0;
for(int j=0; j<10; j++){
System.out.println("The outer loop has iterated " + String.valueOf(j+1) + " times!");
System.out.println("Executing the inner loop");
int local_count = 0;
for(int k=10; k>0; k--){
local_count ++;
total_count ++;
System.out.println("Inner loop #" + String.valueOf(j+1) + " has iterated " + String.valueOf(local_count) + " times!");
System.out.println("The inner loop's total iterations are " + String.valueOf(total_count) + " times!");
}
}
System.out.println("The nested loop iterated " + String.valueOf(total_count) + " times!");
答案 1 :(得分:0)