如何找到二维数组中用户输入像元周围的像元总和?

时间:2019-11-02 00:40:25

标签: c++

到目前为止,我省略了srand(0)以便简化计算,除外部限制外,其他值均接近。输出的格式都正确,但是如果选定的单元格位于第9行或第9行,则周围单元格的总和通常为数百万。

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{

    int matrix[9][9];
    int row_n, col_n, sum, surround_sum, i, j;
    cout << "\t    columns" << endl;
    cout << "       1 2 3 4 5 6 7 8 9 " << endl;
    for (int i = 0; i < 9; i++)
    {
        cout << "row " << i + 1 << "  ";
        for (int j = 0; j < 9; ++j)
        {
            matrix[i][j] = rand() % 10;
            cout << matrix[i][j] << " ";
        }
        cout << endl;
    }
    cout << "what array cell would you like to see? (press enter after each entry)" << endl;
    cout << "row = ";
    cin >> row_n;
    cout << "column = ";
    cin >> col_n;

    cout << "the number " << matrix[row_n - 1][col_n - 1] << " is in cell " << row_n << "," << col_n << endl;

        for (int i=(row_n-2);i<(row_n+1);i++){

            for(int j=(col_n-2);j<(col_n+1);j++){
                if (i>9||i<0)
                    i=0;
                if (j>9||j<0)
                    j=0;
                sum+=matrix[i][j];
                surround_sum= sum-matrix[row_n-1][col_n-1]+2;
            }}
    cout << "the sum of the cells surrounding cell " << row_n << "," << col_n << " is " << surround_sum;

    return 0;
}

0 个答案:

没有答案