簡體   English   中英

在C ++中將for循環轉換為while循環

[英]Converting for loop to do while loop in C++

我需要將此for循環轉換為do:

for (int i = 0; i <= input; i = i + 2)
{
    cout << name << " is number " << input << endl;
    total = total + i;
}
cout << endl;
cout << total << endl;

這是我到目前為止的內容:

do
{
    cout << name << " is number " << input << endl;
    i += 2;
    total += i;
} while (i <= input);
cout << endl;
cout << total << endl;

它的總價值與for循環的價值不同。 我究竟做錯了什么?

您必須將i加到總數上,然后再加2

所以do..while循環應該像這樣:

do
{
    cout << name << " is number " << input << endl;
    total += i;
    i += 2;
} while (i <= input);
cout << endl;
cout << total << endl;

for循環和do-while循環之間的主要區別在於以下事實:

  • For循環執行0次或更多次
  • 但是do-while循環執行1次或多次

例:

int input = 100;

//Will never execute as i is bigger than 5
for (int i = input; i<5; ++i)
    cout << i;

//Will execute only one time as i < 5 is checked only
//after first execution
int i = input;
do
{
    cout << i;
} while(i < 5);

正確執行任務的方法是:

int i = 0;
//if used to prevent first execution
if (i <= input)
{
    do
    {
        cout << name << " is number " << input << endl;
        total = total + i;
        i = i + 2;
    } while(i <= input);
}

但是for最好重寫for循環,例如

for(BEFORE_STATEMENT; FINISH_STATEMENT; ITERATE_STATEMENT)
{
    LOOP_CODE
}

就像while循環一樣

BEFORE_STATEMENT
while(FINISH_STATEMENT)
{
    LOOP_CODE
    ITERATE_STATEMENT
}

你只需要改變

i += 2;
total += i;

total += i;
i += 2;

在您的for循環中:

total = total + i;  

在第一次迭代時, i等於0。 do - while循環中執行do - while的方式,在總加法之前將i設置為2。

如果您在代碼的上一部分中沒有這樣做,則需要在do ... while中初始化i。

另外,在做...的同時,更改順序以使總數在i遞增之前遞增。

您的代碼不正確。 正確是

do
{
    cout << name << " is number " << input << endl;
    total += i;//swap these lines
    i += 2;//
} while (i <= input);
cout << endl;
cout << total << endl;

一會兒將執行至少一次,但我不知道我的值是多少。 你也應該初始化你的i。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM