难以理解 C++ 上的 Do-While 循环
Difficulty Understanding the Do-While Loop on C++
我刚开始使用 C++ 编程几周,但我很难理解 Do-While 循环。具体这段代码我看不懂
#include<iostream>
using namespace std;
int main()
{
int sum = 0;
int y = 0;
do
{
for ( int x = 1; x < 5; x++)
sum = sum + x;
y = y+1;
} while ( y < 3);
cout << sum << endl;
return 0;
}
及其结果:
30
我不知道它是如何产生 30 的,如果我能得到这个特定代码块的解释,那就太好了。谢谢。
你的程序做 10+10+10,因为你写它所以它计算小于 5 的整数的总和。
你说在 y<3 的时候做
这意味着它将对 0 到 2 的值执行此操作
所以它是 1+2+3+4==10
对于值 0,1,2,这是 3 次,结果是 30.
据我所知,代码进入 do 块,它看到 for 循环,执行该循环 4 次,然后继续递增 y,然后该过程再完成 2 次。
#include <iostream>
using namespace std;
int main() {
int sum = 0;
int y = 0;
do {
// the code sees this for loop and executes it 4 times
for (int x = 1; x < 5; x++)
sum = sum + x;
y = y + 1; // you increment y by 1, then the code goes back up and repeats the process 2 more times
} while (y < 3); // execute this block 3 times in total
cout << sum << endl;
}
do ... while (cond)
循环以这种方式工作,即在循环的第一次迭代后检查条件 cond
(因此它至少经过一次迭代)。当您首先进入该循环时,您会遇到 for
循环,它将 1 到 4 范围内的所有整数相加。外循环第一次迭代后 sum
的结果为 10,而 [=14= 的值] 现在是 1,所以我们进入下一次迭代。我们再次在内循环中对所有数字求和,并将结果添加到 sum
的先前结果(即 10),现在结果为 20。我们递增 y
,所以它是 2,条件 y < 3
仍然成立,所以我们进入下一次迭代。我们再次对数字求和,sum
现在是 30,我们递增 y
,所以它是 3。do ... while
循环的条件不再成立,因为 y
现在是 3,不小于 3。此时 sum
是 30,它被打印在标准输出上。
我刚开始使用 C++ 编程几周,但我很难理解 Do-While 循环。具体这段代码我看不懂
#include<iostream>
using namespace std;
int main()
{
int sum = 0;
int y = 0;
do
{
for ( int x = 1; x < 5; x++)
sum = sum + x;
y = y+1;
} while ( y < 3);
cout << sum << endl;
return 0;
}
及其结果:
30
我不知道它是如何产生 30 的,如果我能得到这个特定代码块的解释,那就太好了。谢谢。
你的程序做 10+10+10,因为你写它所以它计算小于 5 的整数的总和。
你说在 y<3 的时候做 这意味着它将对 0 到 2 的值执行此操作 所以它是 1+2+3+4==10 对于值 0,1,2,这是 3 次,结果是 30.
据我所知,代码进入 do 块,它看到 for 循环,执行该循环 4 次,然后继续递增 y,然后该过程再完成 2 次。
#include <iostream>
using namespace std;
int main() {
int sum = 0;
int y = 0;
do {
// the code sees this for loop and executes it 4 times
for (int x = 1; x < 5; x++)
sum = sum + x;
y = y + 1; // you increment y by 1, then the code goes back up and repeats the process 2 more times
} while (y < 3); // execute this block 3 times in total
cout << sum << endl;
}
do ... while (cond)
循环以这种方式工作,即在循环的第一次迭代后检查条件 cond
(因此它至少经过一次迭代)。当您首先进入该循环时,您会遇到 for
循环,它将 1 到 4 范围内的所有整数相加。外循环第一次迭代后 sum
的结果为 10,而 [=14= 的值] 现在是 1,所以我们进入下一次迭代。我们再次在内循环中对所有数字求和,并将结果添加到 sum
的先前结果(即 10),现在结果为 20。我们递增 y
,所以它是 2,条件 y < 3
仍然成立,所以我们进入下一次迭代。我们再次对数字求和,sum
现在是 30,我们递增 y
,所以它是 3。do ... while
循环的条件不再成立,因为 y
现在是 3,不小于 3。此时 sum
是 30,它被打印在标准输出上。