嗨,我正在尝试生成介于(-30,-10)和(10,30)的2组范围之间的随机数,以存储在LinkedList Node中。如果生成的数字为负数,则在列表的“头部”插入此元素和下一个元素(无论其值如何)。如果生成的数字为正,则此元素和下一个元素将存储在“ tail”中。这就是我到目前为止所拥有的。
public class CAO_QUANG_JUIN_P4 {
public static void main(String[] args) {
// TODO Auto-generated method stub
//////////////////////////bloc1:Decleration des variables//////////////////////////
//Create a EVEN N variable between 10 and 30
int N = (int)(Math.random()*20)+10;
N = (N*2)%30;
//Create a simple linkedlist with N nodes
LC e1 = new LC();
LC tete = null;
while(N!=0) {
if(e1==null) {
e1 = new LC();
tete = e1;
e1.data = N;
}
else {
e1.suiv = new LC();
e1.suiv.data = N;
e1 = e1.suiv;
}
N = (int)(Math.random()*20)+10;
int M = (int)(Math.random()*-20)-10;
}
答案 0 :(得分:3)
您有两个选择:
请注意,如果您想要均匀的随机分布,则如果两个范围的大小不相等,则#1会出现问题。
另外请注意,Math.random() * 20
是错误的。
从根本上讲,通过数学证明:
double
具有64位。这意味着它最多可以表示2 ^ 64个数字。那是很多数字,但不是无限数量。解决方案是创建一个Random实例并使用其 IS 真正均匀分布的.nextInt(20)
方法。
Random r = new Random(); // make one instance, once, in your app.
boolean goNegative = r.nextBoolean();
int nr = (goNegative ? -1 : +1) * (10 + r.nextInt(20));
// note, like in your example, 10 is possible,
//but 30 cannot be hit. Make it r.nextInt(21)
//instead if it needs to be.
Random r = new Random(); // make one instance, once, in your app.
int nr = r.nextInt(40);
if (nr < 20) nr -= 29; // all numbers from -29 to -10, inclusive, covered.
else nr -= 10; // covers 10-29 inclusive.
答案 1 :(得分:2)
尝试以下操作:
Random r = new Random();
// the following generates a number between 0 and 20 inclusive and adds 10 to it
int a = r.nextInt(21)+10; // between 10 and 30 inclusive
// the following does the same but changes the sign.
int b = -(r.nextInt(21)+10); // between -10 and -30 inclusive
For the negative one you could also do this.
b = -30+r.nextInt(21);
因此,如果您想从两个集合中随机选择一个,则可以执行以下操作:
int n = nextInt(2) == 0 ? -30+r.nextInt(21) : r.nextInt(21)+10;