解题思路:
1.用一维数组代替二维数组;
2.设Length为二维数组中每行的长度;
3.对应一维数组长度为pow(Length,2);
4.设i代表行数,从1开始;(也可以从0开始,但下面关系式要变)
5.则主对角线上的元素对应在一维数组中的下标与i的关系为:(i-1)*Length+i-1 -------> (Length+1)*(i-1)
6.则副对角线上的元素对应在一维数组中的下标与i的关系为:Length+((i-1)*(Length-1))-1------> i*Length-i---->i*(Length-1)
4
1 2 3 4 i=1
5 6 7 8 i=2
9 10 11 12 i=3
13 14 15 16 i=4
3
1 2 3 i=1
4 5 6 i=2
7 8 9 i=3
对于行数为奇数的二维数组,主,副对角线相交的元素,加了两遍,最后要减去;
参考代码:
#include <stdio.h> #include <malloc.h> #include <math.h> int main() { int *Matrix; //一维数组 int Length, Sum = 0; //二维数组宽度,和 scanf( "%d", &Length ); Matrix = (int *) malloc( pow( Length, 2 ) * sizeof(int) );//分配空间长度pow(Length,2) for ( int i = 0; i < pow( Length, 2 ); i++ ) //输入矩阵 scanf( "%d", &Matrix[i] ); for ( int i = 1; i <= Length; i++ ) Sum += ( (Matrix[(i-1)*(Length+1)]) +(Matrix[i*(Length-1)])); //求和 if ( Length % 2 != 0 ) printf( "%d", Sum - Matrix[2 * Length - 2] ); //Length为奇数减去主副对角共有元素输出 else printf( "%d", Sum ); //Length为偶数直接输出 return(0); }
别忘点赞哦-.-
0.0分
13 人评分
qzfycy 2020-03-25 18:13:12 |
Oj上基本不用free,不需要