简体   繁体   English

生成13至100之间的1000个随机数

[英]Generating 1000 random numbers between 13 and 100

I'm trying to generate 1000 random numbers between 13 and 100. So far it's only generating 75% of what I want repeatedly a thousand times. 我试图生成13到100之间的1000个随机数。到目前为止,它只能重复生成1000次所需的75%。 Here's what I have so far: 这是我到目前为止的内容:

Random rand = new Random();
for (int j = 0; j < 1000; j++)
{
    int pick = rand.nextInt((87) + 13);
    pick++;
}

Why isn't it working? 为什么不起作用?

Pay attention to nextInt() covering the 0 inclusively and the specified value exclusively ! 注意nextInt()覆盖0 以包容和规定值独家 So it has to be rand.nextInt(88) to make the highest int generated be 87. Here is what you want: 因此必须是rand.nextInt(88)才能使生成的最高int为87。这是您想要的:

Random rand = new Random();
for (int j = 0; j<1000; j++)
{
    int pick = rand.nextInt(88)+13;
}

rand.nextInt(88) + 13; should give you numbers between 13 and 100, and you just put it in your loop. 应该为您提供13到100之间的数字,您只需将其放入循环中即可。

The line : 该行:

So far its only generating 75% of what i want repeatedly a thousand times 到目前为止,它只产生了我想要重复一千次的75%

Really doesn't add up to me. 真的不加给我。 It might be a seeding issue you're having though. 不过,这可能是一个播种问题。 Make sure to always re-seed the random number, using time. 确保始终使用时间重新播种随机数。

But I agree with Abdul , you need to take the +13 out of that parenthesis: 但我同意阿卜杜勒(Abdul)的观点,您需要从括号中+13

rand.nextInt(87) + 13;

Because rand.nextInt((87) + 13) is the same as rand.nextInt((67) + 23) as rand.nextInt((1) + 99) 因为rand.nextInt((87) + 13)rand.nextInt((67) + 23)rand.nextInt((1) + 99)

But if you want more "true" randomness, look into something called buzzhash (though that is for hashing ; yet may be modded for number) 但是,如果您想要更多的“真实”随机性,请查看一种称为buzzhash的东西(尽管这是用于散列;但可能会针对数字进行修改)

I use this in my codes: 我在代码中使用了这个:

public static int randomInteger(int min, int max)
{
    java.security.SecureRandom rand = new java.security.SecureRandom();

    //get bounded [0, max) from nextInt()
    int randomNum = rand.nextInt(max) + min;

    return randomNum;
}

value = randomInteger(13,100); //13..99
value = randomInteger(13,101); //13..100

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

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