java如何取得-10到10之间的int型和double型随机数

2024-11-23 08:58:35
推荐回答(2个)
回答1:

// get integer random number:
Random random = new Random();
int nMax = 10;
int nMin = -10;
int nRange = nMax-nMin;
// get a random integer from 0 to nRange;
int nRandomInt = random.nextInt(nRange);
// what you want
int nYouWant = nMax - nRandomInt;
System.out.println(nYouWant);

// get double random number:
Random random = new Random();
Double nMax = 10;
Double nMin = -10;
Double nRange = nMax-nMin;
// get a random double from 0 to nRange;
Double nRandomDouble = random.nextDouble()*nRange;
// what you want
Double nYouWant = nMax - nRandomDouble;
System.out.println(nYouWant);

建议你看看下面的参考资料, 写得比较全. 不过里面说的用%来获取范围的做法我个人觉得有问题,因为nextInt(n)返回0-n, getDouble()返回0-1, 都无法直接得到负数, 还是用Max-Range的方式比较靠谱.

回答2:

gggggggggggggggggggggggggggggggggggg