打印一个简单的2×3矩阵

我对 C++ 很陌生,我有一个小任务是打印一个仅由 0 组成的简单 2x3 矩阵。但是,尽管进行了一些尝试,我还是无法弄清楚如何编码以正确打印矩阵。这是我的代码:

#include <stdlib.h>
#include <iostream>
using namespace std;

int main()
{
    int n_rows = 3;
    int n_cols = 2;

    for (int a = 0; a < n_cols; a++)
        for (int b = 0; b < n_rows; b++)
            cout << "0" << " ";
            cout << "n";

    return 0;
}

我的代码的输出是:

0 0 0 0 0 0 

输出实际上应该是这样的:

0 0 0
0 0 0

谁能描述如何获得正确的输出?谢谢。

回答

您没有在第二个循环中打破界限。您的代码在第一个循环中打破了行。

#include <stdlib.h>
#include <iostream>
using namespace std;

int main()
{
    int n_rows = 3;
    int n_cols = 2;

    for (int a = 0; a < n_cols; a++){
        for (int b = 0; b < n_rows; b++)
            {
               cout << "0" << " ";
            }
             cout << "n";
           } 

    return 0;
}


以上是打印一个简单的2×3矩阵的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>