C ++ ||添加两个matrice数组 - 更简单的输出方式?

时间:2013-03-28 10:43:47

标签: c++ arrays loops matrix format

我正在做一些关于C ++的自学,并且正在做一些关于数组,循环等的章节。有很多练习,而我所引用的练习非常简单。初始化两行和三列的两个矩阵。

输出矩阵的内容(按指定格式),然后执行第三个矩阵中的加法。输出完成后输出第三个数组。我的代码有效,但我认为有更好的方法来输出而不是解决每个matrice元素?我正在考虑另一个循环,因为这是练习前的章节,或者这是否可以接受?

#include <iostream>
#include <string>

using namespace std;

int main()
{
    int amatrix[2][3]=
    {
        {-5, 2, 8},
        {1, 0, 0},
    };

    int bmatrix[2][3]=
    {
        {1, 0, 2},
        {0, 3, -6},
    };

    int cmatrix[2][3]=
    {
        {0, 0, 0},
        {0, 0, 0},
    };

    //add generated matrices
    for (int i = 0; i <= 1; i++)
    {
        for (int j =0; j <= 2; j++)
        {
            cmatrix[i][j]=amatrix[i][j]+bmatrix[i][j];
        }
    }

    //output to screen - NEED ADVICE FROM HERE
    cout << "A= " << endl;
    cout << amatrix[0][0] << ", " << amatrix[0][1] << ", " << amatrix[0][2] << endl;
    cout << amatrix[1][0] << ", " << amatrix[1][1] << ", " << amatrix[1][2] << endl << endl;
    cout << "B= " << endl;
    cout << bmatrix[0][0] << ", " << bmatrix[0][1] << ", " << bmatrix[0][2] << endl;
    cout << bmatrix[1][0] << ", " << bmatrix[1][1] << ", " << bmatrix[1][2] << endl << endl;
    cout << "C= " << endl;
    cout << cmatrix[0][0] << ", " << cmatrix[0][1] << ", " << cmatrix[0][2] << endl;
    cout << cmatrix[1][0] << ", " << cmatrix[1][1] << ", " << cmatrix[1][2] << endl << endl;
}

2 个答案:

答案 0 :(得分:2)

for循环中的

cout << amatrix[i][j]

答案 1 :(得分:0)

使用for之类的循环,类似下面的代码来打印cmatrix

#include <iostream>

// ...

for (int i=0; i < 2; i++)
{
    for (int j=0; j < 3; j++)
    {
        std::cout << cmatrix[i][j] << "\t";
    }
    std::cout << std::endl;
}