如何阅读矩阵并总结起来?

时间:2015-08-08 07:08:41

标签: c++ arrays matrix sum

我想做一个编码,它读取4x4矩阵并总结它们。我不知道我做错了什么。我的结果是它一直要求输入元素。我只想要4x4。任何人都可以帮助我吗?

#include <iostream>
using namespace std;


const int SIZE = 4;
double sumColumn(const double m[][SIZE], int rowSize, int columnIndex)
{
    int sum = 0;
    for (int i = 0; i<SIZE; i++)
    {
        for (int j = 0; j<SIZE; j++)
        {

            sum = sum + m[i][j];
        }

    }
    return sum;
}
int main()
{
    double m[SIZE][SIZE], sum = 0;
    cout << "Enter the elements of the matrix" << endl;
    for (int i = 0; i<SIZE; i++)
        for (int j = 0; j<SIZE; j++)
            cin >> m[i][j];


    sum = sumColumn(m, SIZE, SIZE);

    cout << sum << endl;


    return 0;
}

1 个答案:

答案 0 :(得分:-2)

一个好的做法是使用花括号,即使“for”的内容有一行,但在你的情况下必须采用下一种方式

for (int i = 0; i<SIZE; i++) {
    for (int j = 0; j<SIZE; j++) {
        cin >> m[i][j];
        sum = sumColumn(m, SIZE, SIZE);
    }
}

问候

完整的代码是:

#include <iostream>
using namespace std;

const int SIZE = 4;
double sumColumn(const double m[][SIZE], int rowSize, int columnIndex)
{
    int sum = 0;
    for (int i = 0; i<SIZE; i++)
    {
        for (int j = 0; j<SIZE; j++)
        {
            sum = sum + m[i][j];
        }
    }
    return sum;
}
int main()
{
    double m[SIZE][SIZE], sum = 0;
    cout << "Enter the elements of the matrix" << endl;
    for (int i = 0; i<SIZE; i++) 
    {
        for (int j = 0; j<SIZE; j++) 
        {
            cin >> m[i][j];
            sum = sumColumn(m, SIZE, SIZE);
        }
    }
    cout << sum << endl;
    return 0;
}