java如何取得-10到10之间的int型和double型随机数
答案:2 悬赏:40 手机版
解决时间 2021-11-17 13:13
- 提问者网友:酱爆肉
- 2021-11-16 16:20
java如何取得-10到10之间的int型和double型随机数
最佳答案
- 五星知识达人网友:一叶十三刺
- 2021-11-16 17:14
// 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
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
全部回答
- 1楼网友:廢物販賣機
- 2021-11-16 18:34
gggggggggggggggggggggggggggggggggggg
我要举报
如以上问答信息为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯