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

标签 c++ loops for-loop do-while

我需要将这个 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/

相关文章:

c++ - 转发声明 boost::signals2::signal<void()>

c++ - 添加对共享 ptr 的引用会增加引用计数吗

javascript - 如何动态结束加载动画

windows - 何时以及在批处理文件中的 FOR/F 和 WMIC 中转义什么

Python - 读取矩阵中的第n行

c++ - C++ 中的 Char 到 Int?

c++ - listen() 是连续运行还是我需要循环它以继续接收套接字上的连接?

mysql - SQL - 遍历 MySQL 中的每一行表?

java - 方法执行重试

r - 使用 sapply 进行中值插补