package wzs.arithmetics;
// 题目:求一个3*3矩阵对角线元素之和
public class Test_wzs26
{
public static void main(String[] args)
{
int array[][] =
{
{
1, 2, 3
},
{
4, 5, 6
},
{
7, 8, 9
}
};
System.out.println("打印矩阵:");
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
System.out.print(array[i][j] + "\t");
}
System.out.println();
}
System.out.println("打印出对角元素,并求和.");
int sum = 0;
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
if (i == j)
{
sum += array[i][j];
System.out.print(array[i][j] + "\t");
}
}
}
System.out.println("对角元素和:" + sum);
int sum2 = 0;
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
if (i + j == 2)
{
sum2 += array[i][j];
System.out.print(array[i][j] + "\t");
}
}
}
System.out.println("对角元素和:" + sum2);
}
}
输出结果:
打印矩阵:
123
456
789
打印出对角元素,并求和.
159对角元素和:15
357对角元素和:15