我有两个函数用于递归计算矩阵的行列式。这些值取自 HTML 表单。但是函数没有运行。有人可以帮我解决这个问题吗?我会很感激。
HTML
<form>
element 0_0 <input type = "text" class = "elements"/>
element 0_1 <input type = "text" class = "elements"/>
element 1_0 <input type = "text" class = "elements"/>
element 1_1 <input type = "text" class = "elements"/>
<input type = "button" value = "clickMe" onclick = "determinant('elements','class')"/>
</form>
JavaScript
function create2Darray(clname){
var A = document.getElementsByClassName(clname);
var arr = new Array();
var rows = Math.sqrt(A.length);
for(var i = 0; i < rows; i++){
arr[i] = new Array();
for(var j = 0; j < rows;j++){
arr[i][j] = A[i*rows + j].value;
}
}
return arr;
}
function determinant (matrixClass,type) {
if(type == 'class'){
var matrix = create2Darray(matrixClass);
} else if(type == 'name'){
var matrix = new Array();
}
var det = 0;
if (matrix.length == 1){
return matrix[0][0];
} else if (matrix.length == 2){
return (matrix[0][0] * matrix[1][1]) - (matrix[0][1] * matrix[1][0]);
}
var smaller = new Array();//creating an empty array for a matrix minor;
for (var k = 0; k < matrix.length; k++){
smaller[k] = [];
for(var l = 0;l < matrix.length; l++){
smaller[k][l] = [];
}
}
for (var i = 0; i < matrix.length; i++){
for (a = 1; a < matrix.length; a++) {
for (b = 0; b < matrix.length; b++) {
if (b < i) {
smaller[a - 1][b] = matrix[a][b];
} else if (b > i) {
smaller[a - 1][b - 1] = matrix[a][b];
}
}
}
if (i % 2 == 0) {
s = 1;
} else {
s = -1;
}
det += s * matrix[0][i] * (determinant(smaller,'name'));
}
return det;
alert(det);
}
注意:此递归存在问题。我尝试计算并返回和警告矩阵 2x2 的行列式并且它有效。但是当我尝试使用 3x3 矩阵时它没有。所以请帮忙