是否可以在Java中使用Math.Random()来获取系列中的数字,例如10,20,30,40 ......或100,200,300 .... 我当前的实现是Math.Random()* 3 * 100,因为我认为这会使我的数字达到300,可以被100整除。
答案 0 :(得分:2)
此代码在步骤10中返回一个随机数.0从中排除0,但如果要添加它,请取出Math.random()行上的+1。
int step = 10;
int random = (int)(Math.random()*10+1)*step; //10 is the number of possible outcomes
System.out.println("Random with step " + step + ":" random);
答案 1 :(得分:1)
Math.random()
返回double
。您需要int
值,因此您应该使用Random
类。无论如何你应该这样做。
Random rnd = new Random();
int num = (rnd.nextInt(30) + 1) * 10; // 10, 20, 30, ..., 300
说明:
nextInt(30)
返回0到29之间的随机数(包括)
+ 1
然后将其设为1到30之间的数字
* 10
然后10, 20, 30, ..., 300
。
因此,如果您只想要100, 200, 300
,请使用:
int num = (rnd.nextInt(3) + 1) * 100; // 100, 200, 300
答案 2 :(得分:0)
documentation of Math.random()表示呼叫返回
具有正号的双值,大于或等于0.0且小于1.0。
这意味着,计算结果的数量介于0到300之间,但它不是int
类型,而是类型double
。您应该添加对Math.round的调用,或者只是将其强制转换为int
,如果要创建多个值,则添加一个循环。
答案 3 :(得分:0)
如果你想返回10,20,30,40,50,60等数字......以下内容应该这样做。
int ranNumber=(int)(Math.random()*10+1)*10;
System.out.println(ranNumber);
//sample output: 80
答案 4 :(得分:0)
似乎没有直接的方法可以做到这一点,但我确信通过一些操作,我们可以做到这一点。下面我创建了方法randSeries
来生成基于系列的数字。您向此方法发送两个值,一个增量,即您希望序列号的基数有多大。然后基地,这是你的10s,20s,30s。我们实际上是在您提供方法的范围内生成一个随机数,然后将其乘以您发送方法的基数,以创建一个可被基数整除的值。
public int randSeries(int increment, int base){
Random rand = new Random();
int range = rand.nextInt(increment)+1; //random number
System.out.println(range);
int finalVal = range * base; //turning your random number into a series
System.out.println(finalVal);
return finalVal; //return
}
作为注释:: 此方法可用于生成 ANY 基数值的数量,而不仅仅是10。