<html>
<head>
<script>
function coinFlip() {
return (Math.random() < 0.3) ? 'Heads' : 'Tails';
}
var flipamount = 100;
var countHeads = 0;
var countTails = 0;
for (var i = 0; i < flipamount; i++) {
if (coinFlip() === 'Heads') {
countHeads++;
//document.getElementById("Coin").innerHTML = "Heads";
} else {
countTails++;
//document.getElementById("Coin").innerHTML = "Tails";
}
}
// coinFlip();
//alert("Heads appear "+(countHeads/howManyTimes)*100+"% of the time"); //Code that works
alert("Heads appears " + countHeads + ", Tails appears " + countTails); //Code that works
</script>
</head>
<button type="button" onclick="coinFlip()" id="Coin">CLICK ME</button>
<p>
</p>
</html>
所以我需要制作一个有偏差的硬币翻转器。到目前为止,我已经设法让硬币更偏向于正面或反面,但现在我需要能够在 HTML 中编辑其中一些变量。我必须能够允许用户随意改变概率,并且能够控制用户掷硬币的次数。
我也无法使按钮工作,我只能使用脚本中的警报来显示结果。目前有点陷入困境,希望得到任何帮助。我对 Javascript 也不太有经验。
最佳答案
这非常原始,没有任何错误处理,但应该回答您原来的问题。它具有概率和翻转次数的输入。每组翻转后,您都会记录正面和反面的总数。
我添加了一个在按下按钮后运行的函数,并给出了 <p>
元素一个 ID,以便能够将结果直接写入其中。
//set both heads and tails to zero
var countHeads = 0;
var countTails = 0;
//ternary function to decide between heads or tails
function coinFlip(param) {
return (Math.random() < param) ? 'Heads' : 'Tails';
}
function Execute() {
//takes the value of the number input
var flipamount = Number(document.getElementById("numb").value);
for (var i = 0; i < flipamount; i++) {
//takes the value of the probability input to use in the coinFilp function
if (coinFlip(Number(document.getElementById("prob").value)) === 'Heads') {
//add one to heads if heads comes up
countHeads++;
} else {
//add one to tails if tails comes up
countTails++;
}
}
//write result to the paragraph
document.getElementById("result").innerHTML = "Heads appears " + countHeads + ", Tails appears " + countTails;
}
Probability: <input id="prob" type="number" size="3" min="0.1" max="1" step="0.1" value="0.5" /><br />
Number Flips: <input id="numb" type="number" size="3" min="10" max="100" step="10" value="50" /><br />
<button type="button" onclick="Execute()" id="Coin">CLICK ME</button>
<p id="result"></p>
关于javascript - 用户输入的偏置硬币翻转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58869367/