第八章第五题(代数:两个矩阵相加)(Algebra: adding two matrices)
-
8.5(代数:两个矩阵相加)编写两个矩阵相加的方法。方法头如下:
public static double[][] addMatrix(double[][] a,double[][] b)
为了能够进行相加,两个矩阵必须具有相同的维数,并且元素具有相应或兼容的数据类型。假设c表示相加的结果矩阵,每个元素Cij就是aij+bij。例如,对于两个3x3的矩阵a和b,c有:
编写一个测试程序,提示用户输入两个3x3的矩阵,然后显示他们的和。下面是一个运行示例:
Enter matrix1:1 2 3 4 5 6 7 8 9
Enter matrix2:0 2 4 1 4.5 2.2 1.1 4.3 5.2
The matrices are added as follows
1.0 2.0 3.0 0.0 2.0 4.0 1.0 4.0 7.0
4.0 5.0 6.0 + 1.0 4.5 2.2 = 5.0 9.5 8.2
7.0 8.0 9.0 1.1 4.3 5.2 8.1 12.3 14.2
8.5(Algebra: adding two matrices)Write the method of adding two matrices. The method header is as follows:
public static double[][] addMatrix(double[][] a,double[][] b)
In order to be able to add, the two matrices must have the same dimension and the elements must have corresponding or compatible data types. Suppose C is the result matrix of addition, and each element CIJ is AIJ + bij. For example, for two matrices A and B of 3X3, C has:
Write a test program that prompts the user to enter two 3x3 matrices, and then displays their sum. Here is a running example:
Enter matrix1:1 2 3 4 5 6 7 8 9
Enter matrix2:0 2 4 1 4.5 2.2 1.1 4.3 5.2
The matrices are added as follows
1.0 2.0 3.0 0.0 2.0 4.0 1.0 4.0 7.0
4.0 5.0 6.0 + 1.0 4.5 2.2 = 5.0 9.5 8.2
7.0 8.0 9.0 1.1 4.3 5.2 8.1 12.3 14.2 -
参考代码:
package chapter08; import java.util.Scanner; public class Code_05 { public static void main(String[] args) { Scanner input=new Scanner(System.in); System.out.print("Enter matrix1:"); double[][] matrix1=new double[3][3]; for(int i=0;i<matrix1.length;i++){ for (int j=0;j<matrix1[i].length;j&#