- 好好學Java:從零基礎到項目實戰
- 歐陽燊
- 512字
- 2022-07-27 19:14:52
2.3.2 取隨機數
取整只能對已有數字取整,概率統計卻時常要求生成隨機數,Math庫雖然提供了制造隨機數的random方法,但是該方法僅僅生成小于1的隨機小數(包括0和正小數),并不能直接生成隨機整數。
若想生成隨機整數,則需引入專門的隨機數工具Random,該工具實例化后可調用nextInt方法生成int類型的隨機整數,調用nextLong方法生成long類型的隨機長整數,調用nextFloat方法生成float類型的隨機浮點小數,調用nextDouble方法生成double類型的隨機雙精度小數。特別注意,nextInt與nextLong方法得到的隨機整數可能是負數,而nextFloat與nextDouble方法只會返回正的小數,不會返回負的小數。
因為int類型可表達的數值范圍是-2147483648~2147483647,然而很多時候并不需要這么大的隨機數,往往只需要比較小的隨機數(如小于100的隨機整數),所以此時調用nextInt方法要填寫數值的上限,比如式子“new Random().nextInt(100)”表示生成100以內的隨機整數(0≤隨機整數<100)。
下面是獲取各種隨機數的代碼例子(完整代碼見本章源碼的src\com\arithmetic\math\Rand.java):
double decimal=Math.random(); //生成小于1的隨機小數(包括0和正小數) System.out.println("decimal=" + decimal); int integer=new Random().nextInt(); //生成隨機整數(包括負數) System.out.println("integer=" + integer); long long_integer=new Random().nextLong(); //生成隨機長整數(包括負數) System.out.println("long_integer=" + long_integer); float float_decimal=new Random().nextFloat(); //生成隨機的浮點小數(不包括負數) System.out.println("float_decimal=" + float_decimal); double double_decimal=new Random().nextDouble(); //生成隨機的雙精度小數(不包括負數) System.out.println("double_decimal=" + double_decimal); int hundred=new Random().nextInt(100); //生成100以內的隨機整數(0≤隨機整數<100) System.out.println("hundred=" + hundred);
推薦閱讀
- ASP.NET Core:Cloud-ready,Enterprise Web Application Development
- 潮流:UI設計必修課
- Oracle從新手到高手
- Web交互界面設計與制作(微課版)
- Visual C++串口通信技術詳解(第2版)
- Functional Programming in JavaScript
- Web全棧工程師的自我修養
- JavaScript 程序設計案例教程
- C語言程序設計
- Learning Laravel's Eloquent
- “笨辦法”學C語言
- 寫給程序員的Python教程
- 軟件工程與UML案例解析(第三版)
- Flutter從0基礎到App上線
- Visual FoxPro程序設計實驗教程