java如何取得-10到10之间的int型和double型随机数
发布网友
发布时间:2022-10-10 07:17
我来回答
共2个回答
热心网友
时间:2023-10-03 09:20
// 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的方式比较靠谱.
参考资料:http://blog.csdn.net/herrapfel/article/details/1885016
热心网友
时间:2023-10-03 09:20
gggggggggggggggggggggggggggggggggggg