java 程序设计 3-2 2.二维数组的一种加法运算

来源:互联网 发布:电脑版软件 地图 编辑:程序博客网 时间:2024/06/06 12:40
//编程思路:求出二维数组(行数和列数必须相等)的非对角线元素之和,即求两条对角线之外的元素之和public class TestMatrix {/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stubint[][] a={{1,1,1,1},{1,2,2,1},{1,2,2,1},{1,1,1,1}};//初始化数组如4*4printMatrix(a);//按二维方式输出数组int sum=addMatrix(a);System.out.println("非对角线元素之和:   "+sum);}static void printMatrix(int[][] a){for(int i = 0;i < 4 ;++i){for(int j = 0;j < 4; ++j){System.out.print(a[i][j]+" ");}System.out.println();}}static int addMatrix(int[][] a){int temp,temp1=0,temp2=0,temp3=0;for(int i = 0;i < 4 ;i++){for(int j = 0;j < 4;j++){temp1 =temp1 +  a[i][j];}}for(int i =0,j = 0; i< 4&&j<4; i++,j++){temp2 = temp2 + a[i][j];}for(int i =0,j = 3; i< 4&&j>=0; i++,j--){temp3 = temp3 + a[i][j];}temp = temp1 - temp2 - temp3;return temp;}}

原创粉丝点击