编写一个Java程序,使用for循环查找矩阵的迹。矩阵的迹是其对角线元素之和。在这个Java示例中,我们使用嵌套的for循环来迭代矩阵的行和列。接下来,if(i == j)检查它是否是对角线元素,并将该元素加到迹中。
package NumPrograms;
import java.util.Scanner;
public class MatrixTrace1 {
private static Scanner sc;
public static void main(String[] args) {
int i, j, rows, columns, trace = 0;
sc= new Scanner(System.in);
System.out.print("Enter Matrix Rows and Columns = ");
rows = sc.nextInt();
columns = sc.nextInt();
int[][] Tra_arr = new int[rows][columns];
System.out.println("Please Enter the Matrix Items = ");
for(i = 0; i < rows; i++)
{
for(j = 0; j < columns; j++)
{
Tra_arr[i][j] = sc.nextInt();
}
}
for(i = 0; i < rows; i++)
{
for(j = 0; j < columns; j++)
{
if(i == j)
{
trace = trace + Tra_arr[i][j];
}
}
}
System.out.println("\nThe Trace Of the Matrix = " + trace);
}
}

使用while循环查找矩阵迹的Java程序
package NumPrograms;
import java.util.Scanner;
public class MatrixTrace2 {
private static Scanner sc;
public static void main(String[] args) {
int i, j, rows, columns, trace = 0;
sc= new Scanner(System.in);
System.out.print("Enter Matrix Rows and Columns = ");
rows = sc.nextInt();
columns = sc.nextInt();
int[][] Tra_arr = new int[rows][columns];
System.out.println("Please Enter the Matrix Items = ");
i = 0;
while(i < rows)
{
j = 0;
while(j < columns)
{
Tra_arr[i][j] = sc.nextInt();
j++;
}
i++;
}
i = 0;
while(i < rows)
{
j = 0;
while(j < columns)
{
if(i == j)
{
trace = trace + Tra_arr[i][j];
}
j++;
}
i++;
}
System.out.println("\nThe Trace Of the Matrix = " + trace);
}
}
Enter Matrix Rows and Columns = 3 3
Please Enter the Matrix Items =
10 20 30
40 50 60
70 80 125
The Trace Of the Matrix = 185
这个Java示例使用do while循环来计算和打印给定矩阵的迹。
package NumPrograms;
import java.util.Scanner;
public class MatrixTrace3 {
private static Scanner sc;
public static void main(String[] args) {
int i, j, rows, columns, trace = 0;
sc= new Scanner(System.in);
System.out.print("Enter Matrix Rows and Columns = ");
rows = sc.nextInt();
columns = sc.nextInt();
int[][] Tra_arr = new int[rows][columns];
System.out.println("Please Enter the Matrix Items = ");
i = 0;
do
{
j = 0;
do
{
Tra_arr[i][j] = sc.nextInt();
if(i == j)
{
trace = trace + Tra_arr[i][j];
}
}while(++j < columns);
}while(++i < rows);
System.out.println("\nThe Trace Of the Matrix = " + trace);
}
}
Enter Matrix Rows and Columns = 3 3
Please Enter the Matrix Items =
19 22 45
77 88 125
13 50 500
The Trace Of the Matrix = 607