问题
I've implemented the function:
function coinFlip() {
return(Math.floor(Math.random()*2) === 0) ? 'Heads' : 'Tails';
}
And it's all working fine (I already tested it).
My problem is, how do I make this function so that the probability of getting 'Heads' is 30% while the probability of getting 'Tails' is 70%?
Thanks in advance
回答1:
function coinFlip() {
return(Math.random() < 0.3) ? 'Heads' : 'Tails';
}
回答2:
If one of three toss coin is head it doesn't mean that in 10 toss, there will be 3 heads.. Here is your code with 500 toss (just change the number)
function coinFlip() {
return(Math.random() < 0.3) ? 'Heads' : 'Tails'; //ofc 0.3 is 30% (3/10)
}
var howManyTimes=500;
var countHeads=0;
for (var i=0; i<howManyTimes;i++){
if (coinFlip()==='Heads'){
countHeads++;
}
}
alert("Heads appear "+(countHeads/howManyTimes)*100+"% of the time");
"how to solve a specific percentage problem"
You can't, this is how probability works
来源:https://stackoverflow.com/questions/38175472/javascript-how-to-code-a-heads-tails-with-specific-probability-chance-percentag