所以我有两个函数
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();
}
}