了解do / while循环C ++

问题描述 投票:-3回答:5

我不明白当用户输入'Y'时此循环如何重复。所有的代码都在“ do”部分;重复一次吗?之后,while语句只是一个返回语句。

int main()
{   
   int score1, score2, score3; //three scores
   double average;             // Average score
   char again;                 // To hold Y or N input

   do
   {
       /Get three Scores.
       cout << "Enter 3 scores and i will average them: ";
       cin >> score1 >> score2 >> score 3;

       //calculate and display the average
       average = (score1 + score2 + score 3)/3.0;
       cout << "The average is " << average << :.\n;

       // Does the user want to average another set?
       cout << "Do you want to average another set? (Y/N) ":
       cin >> again;
   } while(again == 'Y' || again == 'y');

    return 0;   

}

教科书的解释太简短了,没有点击我的脑袋。谢谢您的时间。

c++ do-while
5个回答
1
投票

循环的主体从{之后的do开始,到}之前的while结束。

似乎您熟悉while循环,现在您只需要了解do-while循环的结构稍有不同(条件在主体之后而不是之前)。

示例:

while ( condition ) {    // while loop
     body
}

do {                     // do-while loop
    body
} while (condition);     

请注意,它们并不等效,通常根据进行迭代之前或之后检查条件是否更自然来选择一个,而不是另一个。


3
投票

您正在查看的是do-while循环。它与while循环

不同。

从cppreference.com,重点是我的:


'while' loop

while ( <condition> )
{
    // code
}

反复执行一条语句,直到condition的值为false。 测试在每次迭代之前进行。


'do-while' loop

do
{
     // code
} while ( <condition> );

反复执行一条语句,直到表达式的值变为false。 测试在每次迭代后进行。


3
投票

您在做完之后没有while循环。您在任何地方都没有while循环! while只是终止do循环的一种方法。


1
投票

我将其简化为相关部分,并使用伪代码:

do
{
   // do stuff that's irrelevant here
   ask user to type Y or N and store into "again" // that's the cin >> again line
}
while (again is Y or y)

关键是循环运行,直到变量“再次”为Y或y。

然后再次根据用户输入在循环内设置变量。

将这两件事放在一起,您会发现循环一直运行到用户输入Y或y。


1
投票

我知道我缺少了一些东西,但是while循环中什么也没有,输入“ Y”如何使它返回?做应该发生一次然后执行while循环。我不明白是什么使循环返回

while关键字需要一个条件来确定是否应执行其体内的代码。在您的情况下,您给出了一个条件,如果变量again设置为'y'或'Y',则应执行循环。

} while(again == 'Y' || again == 'y');

请参考此link,以获取有关whiledo-while循环结构的详细说明。

© www.soinside.com 2019 - 2024. All rights reserved.