在 Java 中生成随机整数的这段代码有什么问题??? (意外输出)
What is wrong with this code for generating random integers in Java??? (Unexpected Outputs)
下面的代码应该生成从 97 到 122 的随机整数:
for(int x = 0; x < 10; x++) {
int a = (int)(Math.random()*(26 + 97));
System.out.println(a);
}
我得到的输出到处都是。他们低于 97。
以下是其中一次运行的输出:
33
113
87
73
22
25
118
29
16
21
这是一个双亲问题。试试这个。
(int)(Math.random()*26)
给出一个介于 0 和 25 之间的数字(含 0 和 25)。
将 97 添加到该范围内,您将得到 97 到 122 之间的值。
int a = (int)(Math.random()*26) + 97;
下面的代码应该生成从 97 到 122 的随机整数:
for(int x = 0; x < 10; x++) {
int a = (int)(Math.random()*(26 + 97));
System.out.println(a);
}
我得到的输出到处都是。他们低于 97。 以下是其中一次运行的输出:
33
113
87
73
22
25
118
29
16
21
这是一个双亲问题。试试这个。
(int)(Math.random()*26)
给出一个介于 0 和 25 之间的数字(含 0 和 25)。
将 97 添加到该范围内,您将得到 97 到 122 之间的值。
int a = (int)(Math.random()*26) + 97;