创建矩阵,并用1填充主对角线,用2填充副对角线


在Java中,可以使用二维数组表示矩阵。矩阵用于存储和处理具有表格结构的数据。矩阵具有与其相关的几个属性和运算,例如加法、减法、乘法、转置和行列式计算。

根据题目要求,我们需要创建一个矩阵,并用1填充主对角线,用0填充副对角线。

让我们开始吧!

例如

假设我们有一个4*4的矩阵,即4行4列。

对矩阵进行运算后,结果将是

输入矩阵的大小:4

结果矩阵是

1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1

算法

步骤1:定义矩阵的大小。

步骤2:创建一个大小为“size”的方阵。

步骤3:在主对角线上填充1,在副对角线上填充0。

步骤4:打印结果。

多种方法

我们提供了不同方法的解决方案。

  • 使用矩阵元素的静态初始化

  • 使用用户自定义方法

让我们一一查看程序及其输出。

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

方法1:使用数组元素的静态初始化

在这种方法中,矩阵元素将在程序中初始化。然后根据算法创建矩阵,并用1填充主对角线,用0填充副对角线。

示例

import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Define the size of the matrix System.out.print("Enter the size of the matrix: "); int size = scanner.nextInt(); // Create a square matrix of size 'size' int[][] matrix = new int[size][size]; // Filling the matrix for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { if (i == j) { // Filling 1 on the primary diagonal matrix[i][j] = 1; } else if (i + j == size - 1) { // Filling 0 on the secondary diagonal matrix[i][j] = 0; } } } // Print the matrix System.out.println("The resultant matrix is:"); for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { System.out.print(matrix[i][j] + " "); } System.out.println(); } } }

输出

Enter the size of the matrix: 4
The resultant matrix is:
1 0 0 0 
0 1 0 0 
0 0 1 0 
0 0 0 1

方法2:使用用户自定义方法

在这种方法中,矩阵元素将在程序中初始化。然后调用用户自定义方法,并将矩阵作为参数传递,并在方法内部根据算法创建矩阵,并用1填充主对角线,用0填充副对角线。

示例

import java.util.Scanner; public class Main { public static void main(String[] args) { // taking the dimension of the matrix Scanner scanner = new Scanner(System.in); // Define the size of the matrix System.out.print("Enter the size of the matrix: "); int size = scanner.nextInt(); // calling user defined method func(size); } // user defined method public static void func(int size) { // Create a square matrix of size 'size' int[][] matrix = new int[size][size]; // Filling the matrix for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { if (i == j) { // Filling 1 on the primary diagonal matrix[i][j] = 1; } else if (i + j == size - 1) { // Filling 0 on the secondary diagonal matrix[i][j] = 0; } } } // Print the matrix System.out.println("The resultant matrix is:"); for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { System.out.print(matrix[i][j] + " "); } System.out.println(); } } }

输出

Enter the size of the matrix: 5
The resultant matrix is:
1 0 0 0 0 
0 1 0 0 0 
0 0 1 0 0 
0 0 0 1 0 
0 0 0 0 1

在这篇文章中,我们探讨了如何使用Java编程语言创建一个矩阵,并用1填充主对角线,用0填充副对角线。

更新于:2023年8月17日

浏览量:281

启动你的职业生涯

通过完成课程获得认证

开始
广告