Java 用其平方替换矩阵元素
矩阵只是一种按二维结构排列的数据元素的集合。在Java中,具有两个维度的数组可以被视为一个矩阵。
根据问题的陈述,任务是将矩阵元素替换为它们的平方。
让我们深入探讨一下这篇文章,了解如何使用Java编程语言来实现这个任务。
展示一些实例
实例-1
假设原始矩阵为{{8,3,2},{12,7,9},{6,4,10}};
将矩阵元素替换为它们的平方后,结果矩阵将为
64 9 4
144 49 81
36 16 100
实例-2
假设原始矩阵为{{4,3,7}, {2,3,9}, {3,4,9}};
将矩阵元素替换为其平方后,结果矩阵将为
16 9 49
4 9 81
9 16 81
实例-3
假设原矩阵为{{1,2,3},{2,1,3},{3,2,1}};
将矩阵元素替换为其平方后,结果矩阵将会是
1 4 9
4 1 9
9 4 1
步骤
步骤1 - 初始化和声明矩阵。
步骤2 - 创建另一个矩阵来存储平方值。
步骤3 - 将矩阵元素与自身相乘或使用内置的pow()函数来获取平方。
步骤4 - 打印结果。
语法
要在Java中获取任意数字的另一个数字的幂,我们可以使用内置的java.lang.Math.pow()方法。
以下是使用该方法获取2的幂的语法-
double power = math.pow (inputValue,2)
多种方法
我们以不同的方式提供了解决方案。
- 通过使用pow()函数对矩阵进行静态初始化。
-
通过使用用户定义的方法而不使用内置函数。
让我们逐个查看程序及其输出。
方法1:通过使用pow()函数对矩阵进行静态初始化
在这种方法中,矩阵元素将在程序中进行初始化。然后根据算法将矩阵元素替换为其平方。在这里,我们将使用内置的Pow()函数来获得元素的平方。
示例
public class Main {
//main method
public static void main(String args[]){
//Initialising the matrix
int a[][]={{8,3,2},{12,7,9},{6,4,10}};
//creating another matrix to store the square value
int c[][]=new int[3][3];
//Multiplying the matrix element by itself to get the square
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
int element = a[i][j];
c[i][j]+= Math.pow(element,2);
//printing the result
System.out.print(c[i][j]+" ");
}//end of j loop
//new line
System.out.println();
}//end of i loop
}
}
输出
64 9 4
144 49 81
36 16 100
方法2:使用自定义方法而不使用内置函数
在这种方法中,程序将初始化矩阵元素。然后通过将矩阵作为参数传递给一个用户定义的方法,并在方法内根据算法替换矩阵元素为其平方。在这里,我们将元素与自身相乘以获得元素的平方。
示例
public class Main {
//main method
public static void main(String args[]){
//Initialising the matrix
int a[][]={{4,3,7},{2,3,9},{3,4,9}};
//calling user defined method
square(a);
}
//user defined method
static void square(int a[][]) {
//creating another matrix to store the square value
int c[][]=new int[3][3];
//Multiplying the matrix element by itself to get the square
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
c[i][j]+=a[i][j] * a[i][j];
//printing the result
System.out.print(c[i][j]+" ");
}//end of j loop
//new line
System.out.println();
}//end of i loop
}
}
输出
16 9 49
4 9 81
9 16 81
在本文中,我们通过使用Java编程语言,探讨了将矩阵元素替换为其平方的不同方法。