如何得到从2到12的和
how to get the sum form 2 till 12 rolldie?
编写一个脚本来模拟掷两个骰子。脚本应该使用Math。随机掷出第一个骰子,再掷出第二个骰子。然后计算这两个值的和。[注:由于每个骰子都可以显示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>
遍历total
中的所有sum并将它们相加:
var sumOfAllDice = 0;
for(int i=2; i<=12; i++) {
sumOfAllDice += total[i];
}
document.write('<p>'+sumOfAllDice+'</p>');
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();
This is the result!
相关文章:
- javascript函数的:和=之间的区别
- 两个指令创建新的继承的和隔离的作用域-元素得到哪个
- 一次又一次地在新的和相同的选项卡中打开一个url
- 加载侦听器上的函数触发得太早
- 有棱角的、无棱角的和自举的
- 如何用“和”求数组的和;对于“;环
- 为什么parseInt()比Firefox中的*1慢得多
- 为什么严格的模式会让如此简单的动作变得如此不同
- AngularJS数组的和
- Js使用setInterval的动画随着时间的推移变得越来越慢
- 为什么我的代码变得“;10$摘要错误”;
- 砖石结构的图像出现得很奇怪
- 计算2个ember.js属性的和
- Ajax脚本让我的服务器忙得不可开交.让其他人来做这件事
- 为什么字符串搜索的参数表现得像Regex
- javascript中以1,2,3..开头的斐波那契数列偶数的和
- AngularJS秒表在手机上的速度慢得令人难以忍受
- 原型Js中的$$和$
- 如何回显一个Javascript函数的和
- 让我的图像变得更大的滚动,和文本时,点击javascript