【问题标题】:How can make my code display numbers even number on for loop如何让我的代码在 for 循环中显示偶数
【发布时间】:2022-12-17 13:57:52
【问题描述】:
#include <iostream>

using namespace std;

int main(){
    for(int i=0; i<50; I++;) {
        cout<<i<<endl;
    }
    return 0;
}

我真的需要这段代码来执行从 1-50 开始的偶数。我尝试了下面的代码:

#include <iostream>

using namespace std;

int main(){
    for(int i=0; i<50; I++; i%=0) {
        cout<<i<<endl;
    }
    return 0;
}

【问题讨论】:

  • C++ 区分大小写:i 应始终为小写字母,绝不能为大写字母。
  • 提示:i=2是偶数,i += 2;也是偶数

标签: c++ for-loop while-loop


【解决方案1】:

您的 for 循环应该 <=50 以确保它包含 50,而不是仅仅使用 i++ 递增,您可以使用 i+=2,每次递增 2。

这是最终的工作代码:

#include <iostream>
using namespace std;

int main() {

    for (int i = 2; i <= 50; i+=2) {
        cout << i << endl;
    }
    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-23
    • 2015-09-30
    • 2021-10-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多