我需要将此for循环转换为do while:
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循环相同的总值。我做错了什么?
答案 0 :(得分:4)
您需要在将其递增2之前将i添加到总数中
所以do..while循环应该是这样的:
do
{
cout << name << " is number " << input << endl;
total += i;
i += 2;
} while (i <= input);
cout << endl;
cout << total << endl;
答案 1 :(得分:2)
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(BEFORE_STATEMENT; FINISH_STATEMENT; ITERATE_STATEMENT)
{
LOOP_CODE
}
as while循环,它将工作相同的
BEFORE_STATEMENT
while(FINISH_STATEMENT)
{
LOOP_CODE
ITERATE_STATEMENT
}
答案 2 :(得分:1)
您只需要更改
i += 2;
total += i;
到
total += i;
i += 2;
在你的for循环中:
total = total + i;
在第一次迭代时, i
等于0。您在do - while
循环中执行此操作的方式,i
在添加总数之前设置为2。
答案 3 :(得分:0)
如果你还没有在代码的前一部分中这样做,你需要在do ... while中初始化我。
此外,在do ... while中,在i递增之前将顺序更改为总增量。
答案 4 :(得分:0)
您的代码不正确。 Corect是
do
{
cout << name << " is number " << input << endl;
total += i;//swap these lines
i += 2;//
} while (i <= input);
cout << endl;
cout << total << endl;
答案 5 :(得分:-1)