[英]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循环之间的主要区别在于以下事实:
例:
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.