难以理解C++; 我在C++编程中已经有几个星期了,我很难理解Dewhile循环。具体来说,我不理解这段代码 #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; }

难以理解C++; 我在C++编程中已经有几个星期了,我很难理解Dewhile循环。具体来说,我不理解这段代码 #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; },c++,do-while,C++,Do While,我不知道它是如何产生30的,如果我能得到这个特定代码块的解释就好了。谢谢。您的程序执行10+10+10操作,因为您编写的程序执行小于5的整数之和 你说在y的时候做,我看到的是,代码进入do块,它看到for循环,执行该循环4次,然后继续增加y,然后这个过程再做2次 #include <iostream> using namespace std; int main() { int sum = 0; int y = 0; do {

我不知道它是如何产生30的,如果我能得到这个特定代码块的解释就好了。谢谢。

您的程序执行10+10+10操作,因为您编写的程序执行小于5的整数之和


你说在y的时候做,我看到的是,代码进入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;
}
#包括
使用名称空间std;
int main(){
整数和=0;
int y=0;
做{
//代码看到这个for循环并执行它4次
对于(int x=1;x<5;x++)
sum=sum+x;
y=y+1;//将y增加1,然后代码返回并将该过程再重复2次
}while(y<3);//此块总共执行3次

cout
do…当(cond)
循环以这种方式工作时,在循环的第一次迭代后检查条件
cond
(因此它至少经过一次迭代)。当您首先进入该循环时,您会遇到
for
循环,它对1到4范围内的所有整数求和。在外循环的第一次迭代之后,
sum
的结果是10,
y
的值现在是1,因此我们移动到下一次迭代。我们再次对内循环中的所有数字求和,并将结果添加到
sum
(当时是10),现在结果是20。我们增加
y
,所以它是2,条件
y<3
仍然保持不变,所以我们移动到下一个迭代。我们再次求和数字,
sum
现在是30,我们增加
y
,所以它是3。
do…而
循环的条件不再保持不变,因为
y
现在是3,这并不小r大于3。此时,
sum
是30,它被打印在标准输出上。

这个程序将1到4的数字相加,并重复三次。
1+2+3+4==10
,做三次就会得到30。试着在调试器中逐行运行程序。你为什么不试着向我们解释一下你认为它是什么呢请告诉我们您认为结果应该是多少?如果您不知道如何使用调试器,打印不同的值可能会有所帮助。
#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;
}