您的位置:

矩阵对角线代码java(上对角线矩阵)

本文目录一览:

编写一个JAVA程序求一个10行、10列的整型方阵对角线上元素之积。

如果矩阵元素的值较大,可以将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; irows; 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);

}

}

用java定义一个二维数组,用于存储1个3*3矩阵的元素值,求出该矩阵对角线元素之和并输出结果

import java.util.Scanner;

class Main

{

    public static void main(String[] args)

    {

        double[][] matrix=new double[3][3];

        double sum=0;

        Scanner scanner=new Scanner(System.in);

        System.out.println("请输入1个3X3矩阵:");

        for(int i=0;i3;i++)

        {

            for(int j=0;i3;j++)

            {

                matrix[i][j]=scanner.nextDouble();

                if(i==j)

                {

                    sum+=matrix[i][j];

                }

            }

        }

        System.out.println("对角线之和为:"+sum);

    }

}

用java编写一个程序,求如下矩阵对角线之和。

public static void main(String args[]){

int A[][]=new int[4][4]{{9,2,5,9},{2,0,3,7},{15,4,5,6},{8,3,12,5}};

int sum=0;

for(int i=0;i4;i++)

{

sum+=A[i][i];

}

System.out.println("此矩阵主对角线上的元素之和是:"+sum);

}

JAVA随机产生一个5*5的矩阵(0-9之间),分别求出两条对角线及周边元素的和

楼主你好

具体代码如下:

import java.math.*;

public class Test

{

private int[][] a = new int[5][5];

public void getA()

{

for (int i = 0; i 5; i++)

{

for (int j = 0; j 5; j++)

{

a[i][j] = (int)(Math.random() * 10);

}

}

}

public void getSum()

{

int zdj=0,fdj=0,zb=0;//分别是主对角 负对角 周边

getA();

for (int i = 0; i 5; i++)

{

for (int j = 0; j 5; j++)

{

System.out.printf ("%d ",a[i][j]);

if(i==0 || i==4)

{

zb += a[i][j];

}

else

{

if(j==0 || j==4)

{

zb += a[i][j];

}

}

if(j == i)

{

zdj += a[i][j];

}

if((i+j == 4))

{

fdj += a[i][j];

}

}

System.out.println ();

}

System.out.println ("主对角线的和:"+zdj);

System.out.println ("负对角线的和:"+fdj);

System.out.println ("周边之和:"+zb);

}

public static void main(String[] args)

{

Test t = new Test();

t.getSum();

}

}

运行结果如下:

0 3 4 8 7

8 9 7 5 6

1 1 8 5 5

3 5 5 1 7

8 7 2 4 5

主对角线的和:23

负对角线的和:33

周边之和:78

希望能帮助你哈