所以我遇到的问题与根据百分比挑选胜利者有关。
现在对于这个方法,我选择1到0之间的随机小数。示例:[。55或.33] 当我生成这个数字时,将根据随机小数的选择来选择百分比。
示例:
计算数字: 用户1机会> 25%。 用户2机会> 75%。
所以我试图找出如何根据创建的小数选择用户。
我在这里有一些JavaScript代码,我不知道其余的,我愿意接受任何帮助。
<!DOCTYPE html>
<html>
<head>
<script>
function nowGet(){
var picked = Math.random() * (1 - 0) + 0;
var numb1 = .25;
var numb2 = .75;
if(numb1 >= picked && picked <= numb1){
alert("25% chance wins with win %: " + picked);
}else if(numb2 >= picked && picked <= numb2){
alert("75% chance wins with win %: " + picked);
}else{
alert("Nothing was picked. win %: " + picked);
}
}
</script>
</head>
<body>
<h1>My Web Page</h1>
<p id="demo">A Paragraph</p>
<button type="button" onclick="nowGet()">Try it</button>
</body>
</html>
答案 0 :(得分:0)
您要实现的目标是从数组中获取最接近的数字。这是您的问题的绝佳答案:https://stackoverflow.com/a/8584940/612847
根据您的具体情况,这是一个解决方案:
function closest (num, arr) {
var curr = arr[0];
var diff = Math.abs (num - curr);
for (var val = 0; val < arr.length; val++) {
var newdiff = Math.abs (num - arr[val]);
if (newdiff < diff) {
diff = newdiff;
curr = arr[val];
}
}
return curr;
}
var array = [.25, .75];
var number = Math.random();
var winner = closest(number, array);
console.log(winner);