我正在尝试添加两个矩阵,但我的数学错误,我认为我没有关于如何正确理解的想法。我觉得我无法弄清楚这一点,我感到绝对愚蠢,但是我的头疼,而且我全都没有选择
import java.util.Scanner;
public class AddMatrices
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int N = 3;
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++) {
matrix1[i][j] = input.nextDouble();
}
}
System.out.print("Enter matrix2: ");
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();
}
}
double[][] resultMatrix = addMatrix(matrix1, matrix2);
System.out.println("The addition of the matrices is ");
printResult(matrix1, matrix2, resultMatrix, '+');
}
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++)
m1[i][j] += m2[i][j];
}
return result;
}
public static void printResult(double[][] m1, double[][] m2, double[][] m3, char op)
{
for (int i = 0; i < m1.length; i++) {
for (int j = 0; j < m1[0].length; j++) {
System.out.print(" " + m1[i][j]);
}
if (i == m1.length / 2)
System.out.print(" " + op + " ");
else {
System.out.print(" ");
}
for (int j = 0; j < m2[0].length; j++) {
System.out.print(" " + m2[i][j]);
}
if (i == m1.length / 2)
System.out.print(" = ");
else {
System.out.print(" ");
}
for (int j = 0; j < m3[0].length; j++) {
System.out.print(" " + m3[i][j]);
}
System.out.println();
}
}
}
答案 0 :(得分:0)
而不是:
m1[i][j] += m2[i][j];
做的:
result[i][j] = m1[i][j] + m2[i][j];