# 矩阵问题 **题目描述** 编写以下函数: (1)在一个二维数组中形成以下形式的n阶矩阵: ```json [1 1 1 1 1 2 1 1 1 1 3 2 1 1 1 4 3 2 1 1 5 4 3 2 1] ``` (2)去掉靠边的元素,生成新的n-2阶矩阵; (3)求生成的n阶矩阵主对角线上的元素之和; (4)以方阵形式输出数组。 在main函数中调用以上函数进行测试。 **输入** 输入生成矩阵的阶数(n>=2) **输出** 以方阵形式输出生成的n阶矩阵、去掉靠边的元素生成的新的n-2阶矩阵、以及生成的n阶矩阵主对角线上的元素之和,最后一行要回车 **样例输入** ```json 5 ``` **样例输出** ```json Generated matrix: 1 1 1 1 1 2 1 1 1 1 3 2 1 1 1 4 3 2 1 1 5 4 3 2 1 del the elements on the side: 1 1 1 2 1 1 3 2 1 The sum of the diagonal:5 ``` 以下程序实现了这一功能,请你填补空白处内容: ```cpp #include using namespace std; int main() { while (1) { int a; cin >> a; int array[a][a]; for (int i = 0; i < a; i++) for (int j = 0; j < a; j++) { if (j < i) array[i][j] = i + 1 - j; else array[i][j] = 1; } cout << "Generated matrix:" << endl; for (int i = 0; i < a; i++) { for (int j = 0; j < a; j++) { cout << array[i][j]; } cout << endl; } cout << "del the elements on the side:" << endl; for (int i = 1; i < a - 1; i++) { ________________; cout << endl; } int sum = 0; int i, j; for (i = a - 2, j = 1; i >= 1; i--, j++) { sum += array[i][j]; } cout << "The sum of the diagonal:" << sum << endl; } return 0; } ``` ## template ```cpp #include using namespace std; int main() { while (1) { int a; cin >> a; int array[a][a]; for (int i = 0; i < a; i++) for (int j = 0; j < a; j++) { if (j < i) array[i][j] = i + 1 - j; else array[i][j] = 1; } cout << "Generated matrix:" << endl; for (int i = 0; i < a; i++) { for (int j = 0; j < a; j++) { cout << array[i][j]; } cout << endl; } cout << "del the elements on the side:" << endl; for (int i = 1; i < a - 1; i++) { for (int j = 1; j < a - 1; j++) { cout << array[i][j]; } cout << endl; } int sum = 0; int i, j; for (i = a - 2, j = 1; i >= 1; i--, j++) { sum += array[i][j]; } cout << "The sum of the diagonal:" << sum << endl; } return 0; } ``` ## 答案 ```cpp for (int j = 1; j < a - 1; j++) { cout << array[i][j]; } ``` ## 选项 ### A ```cpp for (int j = 1; j < a - 1; j++) { cout << array[i - 1][j - 1]; } ``` ### B ```cpp for (int j = 1; j < a - 1; j++) { cout << array[i + 1][j + 1]; } ``` ### C ```cpp for (int j = 0; j < a; j++) { cout << array[i][j]; } ```