Java 如何将矩阵元素减一
矩阵只不过是将数据元素以二维矩形布局排列而成。在Java中,拥有两个维度的数组可以被视为矩阵。
根据问题描述,我们需要将每个矩阵元素减去“1”。
让我们深入了解如何使用Java编程语言来实现这一操作。
一些示例
示例1
- 假设原始矩阵为{{3,1,2},{2,5,9},{6,3,10}};
-
在给定矩阵中,将元素“1”减去后,结果索引将为 –
2 0 1
1 4 8
5 2 9
示例2
-
假设原矩阵为{{2,1,9},{5,5,7},{3,6,10}};
-
在给定矩阵中减去元素“1”后,结果索引为−
1 0 8
4 4 6
2 5 9
步骤
-
步骤1 - 声明并初始化矩阵。
-
步骤2 - 创建另一个矩阵来存储加法值。
-
步骤3 - 使用 c[i][j] += a[i][j] – 1 将元素”1″从矩阵中减去。
-
步骤4 - 打印结果。
多种方法
我们提供了不同的解决方法。
- 通过静态初始化矩阵
-
通过用户定义的方法
让我们逐个查看程序及其输出。
方法1:通过三元运算符
在这种方法中,矩阵元素将在程序中进行初始化。然后,按照算法,将矩阵元素递减一。
示例
public class Main{
//main method
public static void main(String args[]){
//Initialising the matrix
int a[][]={{3,1,2},{2,5,9},{6,3,10}};
//creating another matrix to store the addition value
int c[][]=new int[3][3];
System.out.println("After decrementing each element by 1:");
//addition of element 1 to the matrix
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
c[i][j]+=a[i][j] - 1;
//printing the result
System.out.print(c[i][j]+" ");
}
//new line
System.out.println();
}
}
}
输出
After decrementing each element by 1:
2 0 1
1 4 8
5 2 9
方法2:使用用户定义的方法
在这种方法中,矩阵元素将在程序中初始化。然后通过将矩阵作为参数传递并在方法内部根据算法递减矩阵元素来调用用户定义的方法。
示例
public class Main{
//main method
public static void main(String args[]){
//Initialising the matrix
int arr[][]={{2,1,9},{5,5,7},{3,6,10}};
//calling user defined method
func(arr);
}
//user defined method
static void func(int[][] arr){
//creating another matrix to store the addition value
int c[][]=new int[3][3];
System.out.println("After decrementing each element by 1:");
//addition of element 1 to the matrix
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
c[i][j]+=arr[i][j] - 1;
//printing the result
System.out.print(c[i][j]+" ");
}
//new line
System.out.println();
}
}
}
输出
After decrementing each element by 1:
1 0 8
4 4 6
2 5 9
本文中,我们使用Java编程语言探索了减少矩阵元素的不同方法。