所以我有两个功能
function toWin(){
console.log('win')
}
function toLose(){
console.log('lose')
}
我如何根据给定的百分比执行每个功能?说100次尝试,toWin()
应该随机执行90次。
我想随时将win_percentage
更改为任何数字。
var win_percentage = 90; // 90 percent
function generateResultRandomly(){
//code to execute either function should be here.
}
[如果还有其他方法可以不用我的方法来获得它,将不胜感激,或者您可以帮助编写算法并将其编码出来。
尝试一下
var win_percentage = 90; // 90 percent
function generateResultRandomly(){
var random = Math.floor(Math.random() * 101); // returns a random integer from 0 to 100
if (random <= win_percentage) {
toWin();
} else {
toLose();
}
}