如何在js矩阵中通过键盘输入数字

时间:2017-01-07 05:24:30

标签: javascript matrix input

我坚持使用我的程序。我必须创建一个矩阵并输入每个单元格的值,然后计算矩阵的两个主要对角线的元素之和。 第一个问题 - 我找不到解决方法如何使用键盘输入的元素制作矩阵。

<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>

2 个答案:

答案 0 :(得分:1)

你差点错过了一个大括号!它应该是这样的

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行,并用你在早期代码中传递mat[i][j]的写入使用的任何函数替换B行

对于对角线求和,您可能会发现this有用它是一个C ++问题,但它也适用于您的情况,那里没有特定的c ++

答案 1 :(得分:0)

所以我解决了一项任务。

<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>