如何在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编程语言将矩阵元素减一的不同方法。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C编程
C++
C#
MongoDB
MySQL
Javascript
PHP