javascript中两个随机变量的总和

时间:2014-02-02 09:34:52

标签: javascript

在我的情况下,每次按toss时,我都要显示 head + tails 的总数,这样在这种情况下折腾也会动态变化。

问题是我如何添加头+尾并在每次点击时显示总数。

这是我的代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
<head>
    <script type="text/javascript">
        <!--
        var heads = 0;
        var tails = 0;

        function toss() {
            var headsField = document.getElementById("heads");
            var tailsField = document.getElementById("tails");

            if (flip()) {
                ++heads;
                headsField.value = heads;
            } else {
                ++tails;
                tailsField.value = tails;
            }
        }
        // end function toss
        function flip() {
            return Math.floor(Math.random() * 9) == 1
        }
        // end function flip
    </script>
    <title></title>
</head>
<body>
    <form action="">
        <table border="1">
            <tr>
                <td>Heads</td>
                <td><input id="heads" type="text"></td>
            </tr>
            <tr>
                <td>Tails</td>
                <td><input id="tails" type="text"></td>
            </tr>
            <tr>
                <td><input onclick="toss()" type="button" value="Toss"></td>
            </tr>
        </table>
    </form>
</body>
</html>

2 个答案:

答案 0 :(得分:1)

添加heads + tails。请参阅Fiddle

新表格行

<tr>
   <td>Total</td>
   <td>
      <input id="total" type="text">
   </td>
</tr>

<强>的JavaScript

var heads = 0;
var tails = 0;

function toss() {
    var headsField = document.getElementById("heads");
    var tailsField = document.getElementById("tails");
    var total = document.getElementById("total");

    if (flip()) {
        headsField.value = ++heads;
    } else {
        tailsField.value = ++tails;
    }

    total.value = (heads + tails);
} // end function toss
function flip() {
    var msg = Math.floor(Math.random() * 9) == 1;
    return msg;
} // end function flip

<强>输出

Html Table

答案 1 :(得分:0)

这是我刚才创建的jsFiddle。也许它对你有用。它模拟通过取一个随机数来翻转硬币并确定它是奇数([H] ead)还是偶数([T] ail):

tmp[i] = ( (Math.floor(Math.random()*10))%2 ? 'H' : 'T' );