0

在 for 循环中生成数字作为条件时,我发现了这个问题。我在我的android程序中使用它。

当我这样做时:

String temp = "";
for (int i = 0; i < new Random().nextInt(1000); i++) {
    temp += i + " ";
}

我总是得到不超过100

但是当我这样做时:

for (int i = 0; i < 10; i++) {
    temp += new Random().nextInt(1000) + " ";
}

我得到了从 0 到 999 的真实随机数。

实际发生了什么?

我知道我可以这样做:

int x = new Random().nextInt(1000);
for (int i = 0; i < x; i++) {
    temp += i + " ";
}

这确实会返回 0-999 的随机数。但我只是想了解为什么第一个代码只返回不超过 100 的数字。

4

7 回答 7

4
for (int i = 0; i < new Random().nextInt(1000); i++) { // here upper limit of i will change time to time.
    temp += i + " ";
}

.

for (int i = 0; i < 10; i++) { // here i increase up to   10
    temp += new Random().nextInt(1000) + " ";
}

.

int x = new Random().nextInt(1000); // here x is random but this will never change while for loop is running
for (int i = 0; i < x; i++) {
    temp += i + " ";
}
于 2013-07-23T10:42:42.953 回答
3

在这段代码中

for (int i = 0; i < new Random().nextInt(1000); i++) {
     temp += i + " ";
}

对于循环的每次迭代,变量 i 都会增加 1,但在 i<100 的给定时间点,有可能随机生成小于“i”的数字,因此循环退出。

于 2013-07-23T10:41:15.800 回答
2

你应该在循环之前初始化随机变量

int max =  new Random().nextInt(1000);
String temp = ""; 
for (int i = 0; i < max; i++)
 {      temp += i + " ";    }
于 2013-07-23T10:41:49.357 回答
2

Java 文档说:

返回介于 0(包括)和指定值(不包括)之间的伪随机、均匀分布的 int 值

所以有可能 i 的值可能大于生成的随机数nextInt()并且循环退出。

当您在 for 循环的每次迭代中创建一个新的 RandomnextInt(1000)时,您将不会获得循环的固定值,它会不断变化,您的输出也会不断变化。

String temp = "";
for (int i = 0; i < new Random().nextInt(1000); i++) { //new random nextInt() called on each iteration
    temp += i + " ";
}

注意:我的程序运行到64

于 2013-07-23T10:43:42.007 回答
1

您的第一个实施...

for (int i = 0; i < new Random().nextInt(1000); i++) {
    temp += i + " ";
}

在每次迭代结束时调用new Random().nextInt(1000)以确定是否该结束循环。相同的代码可以重写如下:

int i = 0;
while (i < new Random().nextInt(1000)) {
    temp += i + " ";
    i++;
}

这可能更好地说明为...

int i = 0;
while (true) {
    if (i < new Random().nextInt(1000)) {
        break;
    }
    temp += i + " ";
    i++;
}

因此,尽管 的值i不断增加,但与之比较的数字却在new Random().nextInt(1000)不断变化。您的比较可能看起来像这样......

if (0 < 981) break;
if (1 < 27) break;
if (2 < 523) break;
if (3 < 225) break;
if (4 < 198) break;
if (5 < 4) break;

在上面的例子中,即使第一次调用new Random().nextInt(1000)返回了一个惊人981的 ,循环也只发生了 5 次,因为在第 6 次迭代开始时,new Random().nextInt(1000)返回了4,它小于5的当前值i

希望这可以帮助!

于 2013-07-23T10:46:57.110 回答
0

Here

String temp = "";
for (int i = 0; i < new Random().nextInt(1000); i++) {
        temp += i + " ";
    }

i may be bigger than 100 but probabilistically is practically impossible. yeah!

于 2013-07-23T10:44:27.327 回答
0

“第一个 for 循环”可能会给出小于 100 的输出数字,但并非总是如此,它会给出从 0 到 Random.nextInt(1000) 方法返回的随机数的一系列数字......

第一种和第三种循环方法的工作原理相同......

但是第二个会从 0 到 999 中选择 9 个随机数,答案是(373 472 7 56 344 423 764 722 554 800)

于 2013-07-23T11:08:50.700 回答