简体   繁体   中英

JavaScript Functions Toss Coin Function Challenge

JavaScript Functions (need help with question 4)

  1. Define a function that simulates tossing a coin. Write your definition here. You can save it in your folder as a text file called tossCoin1.txt

  2. Incorporate your function definition from number one into a program that simulates coin tossing. Call the file tossCoin2.html. Let the program toss the coin each time the user presses the “Toss” button. This means that you will need to have a form in the body of your document. Display the results of the toss in a text input in the form.

  3. Modify the program you just wrote, saving it as tossCoin3.html so that it keeps track of the number of times the coin has been tossed, the number of times heads comes up and the number of times tails comes up.

  4. Modify the program again, saving it as tossCoin4.html so that the user can input the number of times they want to toss the coin. If they input a 1000, it will toss the coin a thousand times and output the number of times heads comes up and the number of times tails comes up.

 <label>How many times do you wat to flip the coin</label> <input type = "number" id = "tosses" required> <input type="submit" onsubmit="flipCoin()" value="Flip Coin"> <p> Results:</p> <p> Heads: <span id="head">0</span></p> <p> Tails: <span id="tail">0</span></p>
  <script>
    var tails = 0;
    var heads = 0;
    var tosses = parseInt(document.getElementById("tosses").value);

    function flipCoin(){
      while (tosses != 0){

        var toss = Math.floor(Math.random() * 2);
        tosses--;

        if(toss == 0){
          heads++;
        } else {
          tails++;
        }
        
        document.getElementById("head").innerHTML = (heads);
        document.getElementById("tail").innerHTML = (tails);
      }
      
    }//flipCoin()
  </script>

This function (after a charitable edit by another user) solves the problem...

 function flipCoin() { let tails = 0; let heads = 0; let tosses = parseInt(document.getElementById('tosses').value); //Loop as many times as the tosses for (var i = 0; i < tosses; i++) { let toss = Math.random(); if (toss < 0.5) { heads++; } else { tails++; } } //for loop //display results document.getElementById("head").innerHTML = (heads); document.getElementById("tail").innerHTML = (tails); } document.getElementById('run').addEventListener("click", flipCoin);
 Tosses: <input id="tosses" value="100" style="width:100px" /> <button id="run">Run</button> <p>Heads: <span id="head"/></p> <p>Tails: <span id="tail"/></p>

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