随机类具有一种在给定范围内生成随机int的方法。例如:Random r = new Random(); int x = r.nextInt(100);这将生成一个大于或等于0且小于100的int数。我想对long数做完全相同的操作。long y = magicRandomLongGenerator(100);随机类仅具有nextLong(),但不允许设置范围。
3 回答

holdtom
TA贡献1805条经验 获得超10个赞
生成范围内数字的标准方法(无实用方法)是对范围使用双精度数:
long range = 1234567L;
Random r = new Random()
long number = (long)(r.nextDouble()*range);
将为您提供介于0(含)和范围(不含)之间的长时间。同样,如果您想要x和y之间的数字:
long x = 1234567L;
long y = 23456789L;
Random r = new Random()
long number = x+((long)(r.nextDouble()*(y-x)));
将为您提供从1234567(含)到123456789(不含)的较长时间
注意:检查括号,因为强制转换为long的优先级高于乘法。
添加回答
举报
0/150
提交
取消