簡體   English   中英

如何使用Math.random生成隨機數給出固定結果

[英]How to generate random numbers the give fixed results using Math.random

我是JAVA的新手,我想我已經搜索了所有問題而沒有找到與我的問題類似的問題。

我想生成隨機數,使用Math.random()返回4個固定數字。 我想得到的數字是:0,90,180和270.換句話說,我想要4個數字,最小值為0,最大值為270,增量為90。

int rand = ((int)(Math.random()*4)) * 90;

讓我們打破它。 Math.random()開始,返回范圍[0,1)中的隨機小數。 (0到0.999999999之間的任何東西......,松散地。)

Math.random()*4 //Gives a random decimal between 0 and 4 (excluding 4)

接下來,讓我們截斷小數。

(int)(Math.random()*4) //Truncates the decimal, resulting in a random int: 0, 1, 2, or 3

最后,我們將在90歲之前多道次。

int rand = ((int)(Math.random()*4)) * 90; //0*90=0, 1*90=90, 2*90=180, or 3*90=270

你最好創建一個java.util.Random對象並重用它:

   Random r = new java.util.Random();
   ...
   int x = r.nextInt(4)*90;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM