【问题标题】:How to write this table in a for loop?如何在 for 循环中编写此表?
【发布时间】:2019-03-11 22:09:55
【问题描述】:

期望的输出:

2
4 2
6 4 2
8 6 4 2

这是我的代码:

for(int i = 0; i <= 7; i += 2) {
    for (int j = 0; j <= i; j += 2) 
        cout << j + 2 << " ";
    cout << endl; 
}

我得到一个错误的答案。

【问题讨论】:

  • Trevor Philip 欢迎来到 Stack Overflow。您的问题已被多次回答,因此请务必接受其中一个。

标签: c++ loops for-loop


【解决方案1】:

您使用双 for 循环的方法是个好主意。这是我的广义尝试,它允许在n 行中打印您想要的内容,而不仅仅是 4:

#include <iostream>
using namespace std;

int main() {
    int n = 4;

    for(int i = 0; i < n; ++i) {
        for(int j = i; j >= 0; --j) {
            cout << 2 * (j + 1) << " ";
        }
        cout << "\n";
    }
    return 0;
}

输出:

2 
4 2 
6 4 2 
8 6 4 2

Live Demo

PS:这种方法最大限度地减少(如果不是消除)幻数的使用。

【讨论】:

    【解决方案2】:

    欢迎来到堆栈溢出。 你只是在你的内部 for 循环中走了一条路

    #include <iostream>
    using namespace std;
    
    int main() 
    {
         for(int i = 0; i <= 7; i += 2){
           for (int j = i; j >= 0; j -= 2) {
            cout << j + 2 << " ";
            }
          cout << endl; 
        }
        return 0;
    }
    

    这会给你想要的输出:

    2 
    4 2 
    6 4 2 
    8 6 4 2 
    

    【讨论】:

      猜你喜欢
      • 2013-07-24
      • 1970-01-01
      • 1970-01-01
      • 2010-09-08
      • 2022-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多