【发布时间】:2019-04-15 07:57:49
【问题描述】:
我有一个静态 matrixMult 和 static matrixAdd 方法和一个静态 matrixDisplay(用于打印结果),我在 Main 函数中写了一个测试示例。
我的目标:我想用这两个静态方法将两个矩阵相乘和相加。
我收到这些错误“变量 C 和 d 可能尚未初始化”。 谁能告诉我,这是什么问题?
public class Matrixmultadd {
static double[][] matrixMult(double[][] A,double[][] B) {
double[][] C; //declar this variable for return the result
//return null if on of matrix are null
if(A == null || B == null){
return null;
}
if(A[1].length == B.length){ //check to be equal columns of A with rows of B
for(int n = 0;n < A.length;n++){//n is numbers of rows of A
for(int k = 0;k < B[n].length;k++){
C[n][k] = 0.0;
for(int l = 0;l < A[n].length;l++){//row n of A multiple in column k of B
C[n][k] += A[n][l] * B[l][k];
}
}
}
return C;
} else {
return null;
}
}
static double[][] matrixAdd(double[][] a,double[][] b) {
//check the rows and columns of a and b are equal
if(a.length == b.length && a[1].length == b[1].length){
double[][] d; //declar this variable for return the result
for(int n = 0;n < b.length;n++){
for(int m = 0;m < b[1].length;m++){
d[n][m] = a[n][m] + b[n][m];
}
}
return d;
}else {
return null;
}
}
static void matrixDisplay(double[][] a){
for(int i = 0; i < a.length;i++){
for(int k = 0;k < a[1].length;k++){
System.out.print(a[i][k] + "\t");
}
System.out.println();
}
}
public static void main(String[] args){
double[][] A = {{1,2,3},{4,5,6}};
double[][] B= {{1,2},{3,4},{5,6}};
double[][] d;
d = matrixMult(A,B);
matrixDisplay(d);
}
}
【问题讨论】:
-
您在 if 块之后执行 return C,但如果该语句从未计算为 true,则不会被实例化
-
@ScaryWombat 实际上
C从未被初始化(实例化),无论A和B的长度是多少;C[n][k] = ...还不够 - 需要C = new double[...][...]
标签: java