简体   繁体   中英

Sum of two random variables in javascript

In my case, I want to display the total of heads+tails , each time I press toss , so that toss in this case will be also changing dynamicaly.

The problem is that how can I add heads+tails and show their total each time I clicks on toss.

Here is my code :

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

Add heads + tails . See Fiddle .

New Table Row

<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

OUTPUT

HTML表

Here's a jsFiddle I created a while ago. Maybe it's useful to you. It simulates flipping a coin by taking a random number and determine if it's odd ([H]ead) or even ([T]ail):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM