2017-01-07 3 views
0

私は自分のプログラムで立ち往生しています。私は行列を作り、すべてのセルの値を入力し、行列の2つの主対角線の要素の合計を計算する必要があります。 第1の問題 - 私はキーボードで入力する要素で行列を作る方法を見つけることができません。キーボードで数字を入力する方法

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

答えて

0

あなたはほとんどそこだけブレースで逃した!.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 
    } 
} 

内部ループは、外側のループ(行)の一つ一つiteraionのために実行し、すべての列を移入します その行に 配列を表示するには、console.log()(デバッグのみ)を使用する必要があります。なぜなら、他の文字列とともに配列を出力すると、他の文字列と同じ文字列に変換されるからです。読み取り可能な形式でループを再度使用するだけで、A行を削除し、B行を任意の関数uに置き換える必要があります「あなたは見つけることが対角線の和のために、以前のコード

mat[i][j]を渡す書き込みのために使用して再this便利な、それはC++質問ですが、それはまた、そこに場合は、++特定のCは何もないあなたのため

+0

Thats is it!どうもありがとう! – xLime

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> 
関連する問題