我写了这个程序来添加两个3x3矩阵;谁能告诉我为什么我的输出会产生2个结果矩阵???
package programExam;
import java.io.*;
import java.util.*;
import java.io.File.*;
import java.util.Scanner;
public class progEx {
public static void main(String[]args){
Scanner input = new Scanner(System.in);
int N = 3;
//get the users input and store it in the two arrays
System.out.println("\nEnter matrix1: \n");
//declare 2 array with the appropriate number of rows
//and columns in them to store the numbers in each matrix.
//this is the first one.
double[][]matrix1 = new double[N][N];
for (int i = 0; i< matrix1.length; i++){
for (int j = 0; j< matrix1[i].length; j++){
matrix1[i][j] = input.nextDouble();
}
}
//get the users input and store it in the two arrays
System.out.println("\nEnter matrix2: \n");
double [][] matrix2 = new double [3][3];
for (int i = 0; i< matrix1.length; i++){
for (int j = 0; j< matrix1[i].length; j++){
matrix2[i][j]= input.nextDouble();
}
}
//call the addMatrix method and pass it the two arrays
System.out.println("The addition of the matrices is: ");
double[][] resultingMatrix = addMatrix(matrix1, matrix2);
}//end of main method
//write the addMatrix method to add the two matrices and display the result
public static double[][] addMatrix(double[][] m1, double[][] m2){
double[][] result = new double[m1.length][m1[0].length];
for (int i = 0; i < result.length; i++) {
for (int j = 0; j < result[0].length; j++){
result[i][j]= m1[i][j] += m2[i][j];
}
}
for (int i = 0; i < m1.length; i++) {
for (int j = 0; j < m1[0].length; j++) {
System.out.print(" " + m1[i][j]);
}
for (int j = 0; j < result[0].length; j++) {
System.out.print(" " + result[i][j]);
}
System.out.println();
}
return result;
}//end of add matrices
//end of class
}
输出:
Enter matrix1:
4 5 1
4 3 2
6 3 9
Enter matrix2:
9 2 4
7 4 2
1 7 5
The addition of the matrices is:
13.0 7.0 5.0 13.0 7.0 5.0
11.0 7.0 4.0 11.0 7.0 4.0
7.0 10.0 14.0 7.0 10.0 14.0
答案 0 :(得分:1)
因为System.out.print
函数中有两个addMatrix()
命令。
我相信这段代码:
for (int i = 0; i < m1.length; i++) {
for (int j = 0; j < m1[0].length; j++) {
System.out.print(" " + m1[i][j]);
}
for (int j = 0; j < result[0].length; j++) {
System.out.print(" " + result[i][j]);
}
System.out.println();
}
应该简单地说:
for (int i = 0; i < result.length; i++) {
for (int j = 0; j < result[0].length; j++) {
System.out.print(" " + result[i][j]);
}
System.out.println();
}
另外,请注意您正在修改同一功能中的矩阵m1
(不经意间,我相信)。在我看来这一行:
result[i][j]= m1[i][j] += m2[i][j];
应该是
result[i][j]= m1[i][j] + m2[i][j];
(请注意+=
已替换为+
)