随机数的Javascript算法 [英] Javascript algorithm for random numbers
问题描述
早上好,所有。谈到这个问题,我是个新手。在此先感谢您的帮助。
我需要以下代码才能提供3个大于0且小于13的唯一数字。
我在回复0或2个答案时遇到问题。
< b>我的尝试:
Good morning, all. I am a newb when it comes to this stuff. Thanks in advance for any help.
I need the following code to deliver 3 unique numbers that are greater than 0 and less than 13.
I keep running into problems with returning a 0 or two answers being the same.
What I have tried:
var numb = Math.floor(Math.random()* 13;
var numb2 = Math.floor(Math.random() * 13;
var numb3 = Math.floor(Math.random() * 13;
if (numb != 0) {
var index = numb;
} else {
var index = 1;
}
if (numb2 != 0 && numb2 != numb) {
var index2 = numb2;
} else {
var index2 = numb + 1;
}
if (numb3 != 0 && numb3 != numb1 && numb3 != numb2) {
var index3 = numb3;
} else if (numb2 + 1 == numb) {
var index3 = numb2 + 2
else {
index3 = numb2 + 1
};
}
document.write(index);
document.write(index2);
document.write(index3);
推荐答案
Math.random()返回0(含)和1(独占)之间的随机数,有一点技巧,你可以有
Math.random() returns a random number between 0 (inclusive) and 1 (exclusive), with a bit of trick, you can have
Math.random()*12+1
将返回1(含)和13(独家)之间的随机数。
这样,那里无需检查是否出现0.
由于您重复使用相同的代码生成多个随机数,因此请将此代码放在函数中以便更好地重复使用代码,例如
that will return a random number between 1 (inclusive) and 13 (exclusive).
In this way, there is no need to check for the occurrence of 0.
Since you are re-using the same code to generate multiple random numbers, put this code in a function for better code re-use, e.g.
function getRndNumb(){
return Math.floor(Math.random()*12+1);
}
最后,要在重复时重复生成随机数,请使用循环,在这种情况下执行...虽然更合适,例如
Lastly, to repeatedly re-generate random numbers when there is duplication, use a loop, in this case do...while is more appropriate, e.g.
do {
numb1 = getRndNumb();
numb2 = getRndNumb();
numb3 = getRndNumb();
} while (numb1 == numb2 || numb1==numb3 || numb2==numb3)
我会留给你把这些作品放在一起。
I shall leave it to you to put together these pieces.
而不是只检查一次数字,在一个循环中检查它们
循环播放JavaScript时[ ^ ]
例如你可以做这样的事情(注意 - 未经测试)
Rather than just checking the numbers once, check them in a while loop
JavaScript while Loop[^]
e.g. you could do something like this (Note - untested)
while (numb1 == numb2 || numb2 == numb3 || numb1 == numb3 || numb1 == 0 || numb2 == 0 || numb3 == 0){
if(numb1 == 0 || numb1 == numb2 || numb1 == numb3){
numb1 = numb1 + 1;
if(numb2 == 0 || numb2 == numb3 || numb2 == numb3){
numb2 = numb2 + 1;
if(numb3 == 0 || numb3 == numb1 || numb3 == numb2){
numb3 = numb3 + 1;
}
这篇关于随机数的Javascript算法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!