简体   繁体   English

在C ++中将for循环转换为while循环

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

I need to convert this for loop to a do while: 我需要将此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;

This is what I have so far: 这是我到目前为止的内容:

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

It doesn't give the same total value as the for loop. 它的总价值与for循环的价值不同。 What am I doing wrong? 我究竟做错了什么?

You have to add i to the total before incrementing it by 2 您必须将i加到总数上,然后再加2

So the do..while loop should be like this: 所以do..while循环应该像这样:

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

The main difference between for loop and do-while loop is the fact that: for循环和do-while循环之间的主要区别在于以下事实:

  • For loop executes 0 or more times For循环执行0次或更多次
  • But the do-while loop executes 1 or more times 但是do-while循环执行1次或多次

Example: 例:

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);

The way to correctly do you task is: 正确执行任务的方法是:

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);
}

But for is better to rewrite for loop like 但是for最好重写for循环,例如

for(BEFORE_STATEMENT; FINISH_STATEMENT; ITERATE_STATEMENT)
{
    LOOP_CODE
}

as while loop, which will work the same 就像while循环一样

BEFORE_STATEMENT
while(FINISH_STATEMENT)
{
    LOOP_CODE
    ITERATE_STATEMENT
}

You just need to change 你只需要改变

i += 2;
total += i;

to

total += i;
i += 2;

In your for loop: 在您的for循环中:

total = total + i;  

i is equal to 0 at the first iteration. 在第一次迭代时, i等于0。 The way you were doing it in the do - while loop, i was set to 2 before the total addition. do - while循环中执行do - while的方式,在总加法之前将i设置为2。

If you haven't done so in a previous portion of the code, you need to initialize i in the do...while. 如果您在代码的上一部分中没有这样做,则需要在do ... while中初始化i。

Also, in the do...while, change the order to have total incremented before i is incremented. 另外,在做...的同时,更改顺序以使总数在i递增之前递增。

Your code is incorrect. 您的代码不正确。 Corect is 正确是

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

a do while will be exectued at least one time, no mather what the value is i is. 一会儿将执行至少一次,但我不知道我的值是多少。 Also you should initialise your i. 你也应该初始化你的i。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM