简体   繁体   English

使用JavaScript的随机数

[英]Random Numbers with JavaScript

I have the following code to generate two random numbers 我有以下代码来生成两个随机数

var attackRoll = Math.floor((Math.random()*6)+1);
var defenceRoll = Math.floor((Math.random()*6)+1);

When I run this code, it will generate two random numbers as expected. 当我运行此代码时,它将按预期生成两个随机数。 The only thing I notice, I wish to just ask to make sure I am not going crazy is... The first variable will always have the higher "Roll" or "Equal I have run this code an output the values so many, many times and not once has the second value been higher than that of the first. 我唯一要注意的是,我只想确保自己不会发疯:...第一个变量将始终具有较高的“ Roll”或“ Equal,我已运行此代码并输出了很多很多值次,第二个值没有一次高于第一个。

Is this just me being silly? 这只是我傻吗? Or have I assigned the random numbers incorrectly? 还是我分配的随机数不正确?

Do you mean that attackRoll is always greater than or equal than defenceRoll ? 您是说attackRoll总是大于或等于defenceRoll吗? Absolutely not . 绝对不会 In fact the probability of one being higher than the other is 实际上,一个人比另一个人高的概率是 50% 50% equal. 等于。

Can you support your claims with a fiddle ? 你能用小提琴来支持你的主张吗? Have you tried in different browser? 您是否尝试过使用其他浏览器?

This appears to be a single user error - take a look at this jsFiddle , and you should find that the second number will be diverse: the same, 这似乎是一个单一用户错误 -查看此jsFiddle ,您应该发现第二个数字会有所不同:相同,
higher, 更高,
or lower 或更低
than the first number. 比第一个数字大。

I'm not sure what you want. 我不确定你想要什么。 To get one dice roll and another that is higher or equal use this: 要获得一个掷骰子而另一个掷骰子更高或相等,请使用以下方法:

var sides = 6;
var firstRoll = Math.floor((Math.random()*sides)+1);
var secondRoll = Math.floor((Math.random()*(sides+1-firstRoll)+firstRoll); // a lucky one :)

If you want to rolls and have the higher in the first variable, use 如果您想滚动并且在第一个变量中具有较高的值,请使用

var sides = 6;
var firstRoll = Math.floor((Math.random()*sides)+1);
var secondRoll = Math.floor((Math.random()*sides)+1);
if (firstRoll >= secondRoll) {
    higherRoll = firstRoll; // attackRoll
    lesserRoll = secondRoll; // defenceRoll
} else {
    higherRoll = secondRoll; // attackRoll
    lesserRoll = firstRoll; // defenceRoll
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM