编程生成一个N阶矩阵,使其主对角线相邻上元素皆为1,与主对角线左侧相邻元素皆为2,其余元素皆为0.java
时间: 2024-03-06 17:52:00 浏览: 101
以下是 Java 代码实现:
```java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入矩阵的阶数:");
int n = scanner.nextInt();
// 生成空矩阵
int[][] matrix = new int[n][n];
// 填充主对角线
for (int i = 0; i < n; i++) {
matrix[i][i] = 1;
if (i > 0) {
matrix[i][i-1] = 2;
}
if (i < n-1) {
matrix[i][i+1] = 2;
}
}
// 输出矩阵
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
}
```
例如当输入矩阵的阶数为5时,输出的矩阵为:
```
1 2 0 0 0
2 1 2 0 0
0 2 1 2 0
0 0 2 1 2
0 0 0 2 1
```
阅读全文