javascript - 根据给定的百分比执行功能
问题描述
所以我有两个功能
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();
}
}
推荐阅读
- reactjs - react-dates 根据站点语言使用自定义标签更改工作日标签
- vb.net - 如何比较多个文本框的值
- qt - Detecting gestures out of touch points
- payment-gateway - 通过 API 创建订阅计划
- angular - Angular 不在打字稿中呈现 html
- spring - Chaining multiple Spring Batch readers?
- excel - VBA Auto Vlookup 可以在多个不同的工作表中使用可变范围,可以吗?
- url - How to add an additional value to a Shopify checkout URL?
- azure - MSAL 和 AndroidX 不兼容?
- spotfire - 如何计算spotfire报告中交叉表中空单元格所在的字段