如何获得2到12年的总和?

时间:2015-05-25 16:19:17

标签: javascript

编写一个脚本来模拟两个骰子的滚动。该脚本应该使用Math.random来滚动第一个骰子并再次滚动第二个骰子。然后应计算两个值的总和。 [注意:由于每个骰子可以显示1到6的整数值,因此值的总和将在2到12之间变化,其中7是最频繁的总和,2和12是最不频繁的总和]。 你的程序应该掷骰子5000次。使用一维数组计算每个可能总和出现的次数。在HTML5表格中显示结果。

我只有总和,任何人都可以告诉我如何在表格中获得2到12的滚模总和

    var total = [ , , 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
    var dice1;
    var dice2;
    for (var x = 1; x <= 5000; x++)
    {
    dice1 = rollDie();
    dice2 = rollDie();
    ++total[dice1+ dice2];
    }
    outputResults();
    function rollDie()
    {
    return Math.floor(1 + Math.random() * 6);
    }
    function outputResults()
    {
    document.write( "<table border = \"1\">" );
    document.write("<tr><th width = '100'>Sum of Dice" +"<th width = \"200\">Total Times Rolled</tr>" );
    for ( var i = 2; i < total.length; i++ )
    document.write( "<tr><td>" + i + "<td>" +total[ i ] + "</tr>" );
    document.write( "</table>" )
    document.write( "<br>" );
    document.write( "<br>" );
    document.write( "<table border = \"1\">" );
    document.write("<tr><th width = '100'>Sum of Dice" +"<th width = \"200\">Total Times Rolled</tr>" );
    for ( var i = 2; i < total.length; i++ )
    document.write( "<tr><td>" + i + "<td>" +total[ i ] + "</tr>" );
    document.write( "</table>" );
    }
    <p id="jareb"></p>

2 个答案:

答案 0 :(得分:2)

循环遍历total中的每个总和并将它们加在一起:

var sumOfAllDice = 0;

for(int i=2; i<=12; i++) {
   sumOfAllDice += total[i];
}

document.write('<p>'+sumOfAllDice+'</p>');

答案 1 :(得分:1)

&#13;
&#13;
var total = [,,0,0,0,0,0,0,0,0,0,0,0,0]
var count = [,,0,0,0,0,0,0,0,0,0,0,0,0]

function write(){
  var html="";
  for(var i=2; i<=12; i++){
    html += ("The Sum of "+i+" occurred :"+count[i]+" Times and Total : " + total[i] + "<br/>");
  }
  
  document.write(html);
}


function roll(){
  var d1 = Math.floor(1 + Math.random() * 6);
  var d2 = Math.floor(1 + Math.random() * 6);
  count[d1+d2]++;
  total[d1+d2] += d1+d2;
}






for(i=1;i<=5000;i++)
  roll();

write();
&#13;
This is the result!
&#13;
&#13;
&#13;