我正在研究java加法,减法和乘法程序。我已经创建并完成了程序,但是乘法的输出是错误的,而且我想检查矩阵乘法中第一个矩阵的行是否等于第二个。
import java.util.*;
class matrix
{
public static void matrix_oper(int A[][],int B[][],int m, int n, int p, int q)
{
int[][] C = new int[m][n];
System.out.println("Matrix A: ");
for(int i=0 ; i < A.length ; i++)
{
System.out.println();
for(int j=0 ; j < A[i].length ; j++)
{
System.out.print(A[i][j]+" ");
}
}
System.out.println();
System.out.println();
System.out.println("Matrix B: ");
for(int i=0 ; i < B.length ; i++)
{
System.out.println();
for(int j=0 ; j < B[i].length ; j++)
{
System.out.print(B[i][j]+" ");
}
}
System.out.println();
System.out.println();
System.out.println("Addition Of Matrices: ");
for(int i=0;i<C.length;i++)
{
for(int j=0;j<C[i].length;j++)
{
C[i][j]=A[i][j]+B[i][j];
System.out.print(C[i][j]+" ");
}
System.out.println();
}
System.out.println();
System.out.println();
System.out.println("Substraction Of Matrices: ");
for(int i=0;i<C.length;i++)
{
for(int j=0;j<C[i].length;j++)
{
C[i][j]=A[i][j]-B[i][j];
System.out.print(C[i][j]+" ");
}
System.out.println();
}
System.out.println();
System.out.println();
System.out.println("Multiplication Of Matrices: ");
for(int i=0;i<C.length;i++)
{
for(int j=0;j<C[i].length;j++)
{
C[i][j]=A[i][j]*B[j][i];
System.out.print(C[i][j]+" ");
}
System.out.println();
}
}
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter Number of rows: ");
int m = input.nextInt();
System.out.print("Enter Number of columns: ");
int n = input.nextInt();
int[][] A = new int[m][n];
System.out.print("Enter Number of rows: ");
int p = input.nextInt();
System.out.print("Enter Number of columns: ");
int q = input.nextInt();
int[][] B = new int[p][q];
System.out.println("Enter elements for matrix A : ");
for(int i=0 ; i < A.length ; i++)
for(int j=0 ; j < A[i].length ; j++)
{
A[i][j] = input.nextInt();
}
System.out.println("Enter elements for matrix B : ");
for (int i=0 ; i < B.length ; i++)
for (int j=0 ; j < B[i].length ; j++)
{
B[i][j] = input.nextInt();
}
matrix mx=new matrix();
mx.matrix_oper(A,B,m,n,p,q);
}
}
这个的输出是:
Enter Number of rows: 2
Enter Number of columns: 2
Enter elements for matrix A :
1
1
1
1
Enter elements for matrix B :
2
2
2
2
Matrix A:
1 1
1 1
Matrix B:
2 2
2 2
Addition Of Matrices:
3 3
3 3
Substraction Of Matrices:
-1 -1
-1 -1
Multiplication Of Matrices:
2 2
2 2
我的矩阵乘法有什么错误?