我目前正在嘗試以 100 為步長獲取 100 到 2000 之間的隨機整數,例如 300、800、1400 等。
那就是我發現在一個范圍內獲得一個亂數的方法,但是我如何設法以 100 為步長獲得一個亂數?
Random random = new Random();
int start = 100;
int end = 2000;
int result = random.nextInt(start - end) start;
uj5u.com熱心網友回復:
問題是您是否要包含 2000。以及步長是否正好達到2000。計算只需要包括步長:
Random random = new Random();
final int start = 100;
final int end = 2000;
final int step = 100;
int result = start step * random.nextInt((end - start)/step); // end excl.
int result = start step * random.nextInt((end - start)/step 1); // end incl.
正如已經評論的那樣,將所有內容都基于 1 到 20 之間的亂數并按比例放大可能會更清楚。
int result = (1 random.nextInt(20)) * 100; // 100 upto 2000 by 100.
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/537784.html
標籤:爪哇数学整数
上一篇:從字串中決議長格式日期
