首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何用键盘输入js矩阵中的数字

如何用键盘输入js矩阵中的数字
EN

Stack Overflow用户
提问于 2017-01-07 05:24:29
回答 2查看 1.4K关注 0票数 1

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

代码语言:javascript
复制
<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>
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-01-07 06:51:51

你差点错过了!.It应该是这样的

代码语言:javascript
复制
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++

票数 1
EN

Stack Overflow用户

发布于 2017-01-07 10:32:39

我解决了一项任务。

代码语言:javascript
复制
<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>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41518122

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档