首页 > 解决方案 > 根据给定的百分比执行功能

问题描述

所以我有两个功能

   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.
   }

如果有任何其他方法可以在没有我的方法的情况下得到这个,我们将不胜感激,或者你可以帮助编写算法,我将其编码出来。

标签: javascriptalgorithmpercentage

解决方案


尝试这个

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();
  }
}

推荐阅读