我需要将这个 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 循环相同的总值。我做错了什么?
最佳答案
在将它递增 2 之前,你必须将 i 添加到总数中
所以 do..while 循环应该是这样的:
do
{
cout << name << " is number " << input << endl;
total += i;
i += 2;
} while (i <= input);
cout << endl;
cout << total << endl;
关于c++ - 在 C++ 中将 for 循环转换为 while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9997277/