这是我的看法。我来晚了,因为您已经接受了解决方案;不过,我想向您展示一些东西。例如,如果您将这些矩阵视为一维数组,您可以只用一个函数测试所有大小的矩阵,因为大小不必“内置”到函数定义中的数据类型中。并且我已经评论了很多,希望尽可能的说清楚。
#include <iostream>
#include <algorithm>
// I store matrices as a monodimensional array, so that it is easier to deal
// with matrices of different sizes in the same program, because you can do
// everything with one function. Moreover, I use only one argument here, to make
// it clear that we are dealing with square matrices.
void printHemisphere(int* matrix, int last_row)
{
int last_column = last_row; // It's a square matrix, so they are the same.
// Still, distinguishing between last_column
// and last_row can make the algorithm clearer,
// so I have kept both
// In general I prefer to use "row" and "column" as variable names, instead
// of "i" and "j"
// Our rows go from 0 to last_row-1, but since the first and last one can
// certainly not be used, we can skip them: we start at row = 1, and we stop
// at last_row - 2 (that is, the last one for which row < last_row - 1)
for(int row = 1; row < last_row - 1 ; row++)
{
// We want to start from the cell to the right of the rightmost diagonal.
// The main diagonal has column = row;
// The secondary diagonal has column = last_row - 1 - row
// The rightmost one is the maximum of these 2.
// Then, we want to take the cell to the right of the diagonal, so we
// have to add 1 more.
// All in all we have:
for (int column = std::max(row, last_row - 1 - row) + 1;
column < last_column;
column++)
{
// since this is a 1-D array we have to access it this way
std::cout << matrix[row*last_row+column] << " ";
}
std::cout << std::endl;
}
std::cout << std::endl;
}
int main(int argc, char const *argv[])
{
// Since I am working with monodimensional arrays, I don't store them as
// int matrix3[3][3], but rather as int matrix3[9], which I have expressed as
// int matrix3[3*3] for clarity.
//For each one I have indicated the expected output.
// Expected output:
// 6
int matrix3[3*3] =
{
1, 2, 3,
4, 5, 6,
7, 8, 9
};
// Expected output:
// 8
// 12
int matrix4[4*4] =
{
1, 2, 3, 4,
5, 6, 7, 8,
9, 10, 11, 12,
13, 14, 15, 16
};
// Expected output:
// 10
// 14 15
// 20
int matrix5[5*5] = {
1, 2, 3, 4, 5,
6, 7, 8, 9, 10,
11, 12, 13, 14, 15,
16, 17, 18, 19, 20,
21, 22, 23, 24, 25
};
// Expected output:
// 12
// 17 18
// 23 24
// 30
int matrix6[6*6] = {
1, 2, 3, 4, 5, 6,
7, 8, 9, 10, 11, 12,
13, 14, 15, 16, 17, 18,
19, 20, 21, 22, 23, 24,
25, 26, 27, 28, 29, 30,
31, 32, 33, 34, 35, 36
};
// Expected output:
// 14
// 20 21
// 26 27 28
// 34 35
// 42
int matrix7[7*7] = {
1, 2, 3, 4, 5, 6, 7,
8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21,
22, 23, 24, 25, 26, 27, 28,
29, 30, 31, 32, 33, 34, 35,
36, 37, 38, 39, 40, 41, 42,
43, 44, 45, 46, 47, 48, 49
};
printHemisphere(matrix3, 3);
printHemisphere(matrix4, 4);
printHemisphere(matrix5, 5);
printHemisphere(matrix6, 6);
printHemisphere(matrix7, 7);
return 0;
}
我已经在 ideone 上验证了它,它可以工作。我唯一想补充的是:为确保代码正常工作,请确保使用奇数大小和偶数大小的矩阵对其进行测试。