说几率的几率? [英] Percentage chance of saying something?

查看:88
本文介绍了说几率的几率?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何做到..

  • 80%的时间会说sendMessage("hi");
  • 5%的时间会说sendMessage("bye");
  • 以及15%的时间会说sendMessage("Test");
  • 80% of the time it will say sendMessage("hi");
  • 5 % of the time it will say sendMessage("bye");
  • and 15% of the time it will say sendMessage("Test");

它必须与Math.random()做些事情吗? 像

Does it have to do something with Math.random()? like

if (Math.random() * 100 < 80) {
sendMessage("hi");
}
else if (Math.random() * 100 < 5) {
sendMessage("bye");
}

推荐答案

是的,Math.random()是实现此目的的绝佳方法.您要做的是计算一个随机数,然后根据该数字做出决定:

Yes, Math.random() is an excellent way to accomplish this. What you want to do is compute a single random number, and then make decisions based on that:

var d = Math.random();
if (d < 0.5)
    // 50% chance of being here
else if (d < 0.7)
    // 20% chance of being here
else
    // 30% chance of being here

这样,您就不会错过任何可能性.

That way you don't miss any possibilities.

这篇关于说几率的几率?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆