我正在使用帶有種子的 java.util.random(new Random(System.currentTimeMillis())我需要將其轉換為 int(我的業務邏輯)我嘗試使用 .nextInt(),但沒有幫助//我的業務邏輯--下面的代碼是循環的,目的是每次生成不同的隨機數//int randomNumber=(int) Math.floor(inputParam1 * (new Random(System.currentTimeMillis())).nextInt()));預期輸出:每次生成一個新的隨機數,int格式實際輸出: - 使用 nextInt() 它每次生成相同的數字 - 如果不轉換為 Int,我無法將“隨機”數據類型與上面顯示的 int 變量一起使用
3 回答

泛舟湖上清波郎朗
TA貢獻1818條經驗 獲得超3個贊
不要在每次要生成 Double 時都創建 Random 的新實例。
您可以創建一個實例,然后在需要新的替身時調用它。
Random rand = new Random(System.currentTimeMillis());
// loop starts here
double randomNumber = Math.floor(inputParam1 * rand.nextDouble());
// If you want an integer up to inputParam1 as it seems, you can do:
int randomInt = (int) randomNumber;
您也可以Math.random()像已經建議的那樣使用。

ITMISS
TA貢獻1871條經驗 獲得超8個贊
將下面的代碼轉換為 int 是沒有意義的。
Math.floor(inputParam1 * (new Random(System.currentTimeMillis())).nextDouble()))
請檢查這個答案Using Random Number Generator with Current Time vs without
上面鏈接中最重要的部分:
如果你希望你的隨機序列在運行之間是相同的,你可以指定一個種子。

白板的微信
TA貢獻1883條經驗 獲得超3個贊
我不知道你為什么要把它轉換成 int
雙隨機數=新隨機(System.currentTimeMillis()).nextDouble();這將給出一個介于 0 和 1 之間的隨機雙數
添加回答
舉報
0/150
提交
取消