[英]How to find a Random Value with negative increments, and positive & negative values in Java?
對於下面的數據集,我如何才能找到該集合之間的隨機數,特別是使用 math.random function。
-12, -8, -4, 0, 4, 8, 12
int secondCase = (int)(Math.random()*7)*(-4)-12;
我一直在嘗試上面的代碼和其他東西,但它對我不起作用
我認為你不能用 Math.random() 來做,因為這個方法返回一個帶正號的雙精度值,大於等於 0.0 小於 1.0。
也許,你可以嘗試這樣的事情:
int[] desiredValues = {-12, -8, -4, 0, 4, 8, 12};
Random random = new Random();
for (int i = 0; i < 100; i++) {
int randomIndexBetweenZeroToSix = random.nextInt(7);
System.out.println("random index: " + randomIndexBetweenZeroToSix);
System.out.println("desired value: " + desiredValues[randomIndexBetweenZeroToSix]);
}
在這個例子中,我只是打印數組的隨機索引和基於隨機索引的數組值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.