我坚持我的计划。我必须建立一个矩阵,并输入每个单元格的值,然后计算矩阵的两个主要对角线的元素之和。第一个问题-我找不到解决办法,如何用键盘输入的元素来制作矩阵。
<meta charset="windows-1251">
<script>
//10. A real square matrix of size n x n. Calculate the sum of the elements of the two main diagonals of the matrix.
var r,c; //r - rows, c - columns
r = prompt('Enter the number of rows');
c = prompt('Enter the number of columns');
var mat = [];
for (var i=0; i<r; i++){
mat[i] = [];
}
for (var j=0; j<c; j++){
mat[i][j]= prompt ('Enter a value for the cell ' + i + 'x' + j)
}
document.write(' <XMP> ');
document.write('Matrix \t' + mat + '\r');
document.write('</XMP>');
</script>发布于 2017-01-07 06:51:51
你差点错过了!.It应该是这样的
for (var i=0; i<r; i++){
mat[i] = []; // A
for (var j=0; j<c; j++){
mat[i][j]= prompt ('Enter a value for the cell ' + i + 'x' + j); // B
}
}内环将为外部循环(行)的每一个迭代运行,并填充该行中的每一列以显示数组,您应该使用console.log() (仅用于调试),因为如果您与其他字符串一起打印数组,则它将被转换为字符串,这仅仅是它的名称,以可读的形式为用户或文件松开所有其他内容,您需要再次使用循环,只需删除A行,并将B行替换为您在早期代码中用来写入mat[i][j]的任何函数。
对于对角线和,您可能会发现this很有用,这是一个C++问题,但也适用于您,在这里没有任何特定的c++
发布于 2017-01-07 10:32:39
我解决了一项任务。
<meta charset="windows-1251">
<script>
//10. A real square matrix of size n x n. Calculate the sum of the elements of the two main diagonals of the matrix.
var r,c,d1,d2; //r - rows, c - columns, d1 - first diagonal, d2 - second diagonal
d1 = 0;
d2 = 0;
r = prompt('Enter the number of rows');
c = prompt('Enter the number of columns');
var mat = [];
for (var i=0; i<r; i++){
mat[i] = [];
for (var j=0; j<c; j++){
mat[i][j]= prompt ('Enter a value for the cell ' + i + 'x' + j);
if (i == j){
d1 = +d1 + +mat[i][j];
}
if (i+j == +r-1){
d2 = +d2 + +mat[i][j];
}
}
}
document.write('Diagonal 1 = ' + d1 + "<br>" + 'Diagonal 2 = ' + d2 + "<br>");
</script>https://stackoverflow.com/questions/41518122
复制相似问题