编写一个JAVA程序求一个10行、10列的整型方阵对角线上元素之积。
1个回答
展开全部
如果矩阵元素的值较大,可以将long改为double。
public class Test{
public static void main(String args[]){
int[][] arr = {{1,2,3,4,5,6,7,8,9,10},
{2,3,4,5,6,7,8,9,10,1},
{3,4,5,6,7,8,9,10,1,2},
{4,5,6,7,8,9,10,1,2,3},
{5,6,7,8,9,10,1,2,3,4},
{6,7,8,9,10,1,2,3,4,5},
{7,8,9,10,1,2,3,4,5,6},
{8,9,10,1,2,3,4,5,6,7},
{9,10,1,2,3,4,5,6,7,8},
{10,1,2,3,4,5,6,7,8,9}};
int i;
int rows = arr.length;
long product = 1;
for(i=0; i<rows; i++){
product *= arr[i][i] * arr[i][rows-i-1];
}
if(rows%2==1 && arr[rows/2][rows/2]!=0){ //去年交叉点的重复元素
product /= arr[rows/2][rows/2];
}
System.out.println("10阶矩阵的两条对角线元素之积为 " + product);
}
}
public class Test{
public static void main(String args[]){
int[][] arr = {{1,2,3,4,5,6,7,8,9,10},
{2,3,4,5,6,7,8,9,10,1},
{3,4,5,6,7,8,9,10,1,2},
{4,5,6,7,8,9,10,1,2,3},
{5,6,7,8,9,10,1,2,3,4},
{6,7,8,9,10,1,2,3,4,5},
{7,8,9,10,1,2,3,4,5,6},
{8,9,10,1,2,3,4,5,6,7},
{9,10,1,2,3,4,5,6,7,8},
{10,1,2,3,4,5,6,7,8,9}};
int i;
int rows = arr.length;
long product = 1;
for(i=0; i<rows; i++){
product *= arr[i][i] * arr[i][rows-i-1];
}
if(rows%2==1 && arr[rows/2][rows/2]!=0){ //去年交叉点的重复元素
product /= arr[rows/2][rows/2];
}
System.out.println("10阶矩阵的两条对角线元素之积为 " + product);
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询