2011-12-22 40 views
11

你如何使用Math.random生成隨機整數?如何使用math.random生成隨機整數?

我的代碼是:

int abc= (Math.random()*100); 
System.out.println(abc); 

所有它打印出來是0,我怎麼能解決這個問題?

+7

代碼應該不打印0,它不應該編譯。 – 2011-12-22 22:57:57

+0

eclipse允許它 – 2011-12-23 01:34:14

+0

那是什麼版本?第一行給我「Type mismatch:can not convert double to int」,這是我所期望的。 – 2011-12-23 10:57:06

回答

21

將abc轉換爲整數。

(int)(Math.random()*100); 
+8

應該指出的是,這會產生0-99 – 2011-12-22 23:00:57

+0

只需加一個:(int)(Math.random()* 100 + 1)) ; – Russell 2011-12-31 00:52:20

+0

如果需要一個3位數的隨機數,乘以1000,依此類推...... – Sizzler 2016-05-19 05:07:57

11

作爲替代方案,如果有沒有一個具體的理由使用Math.random(),使用Random.nextInt()

Random rnd = new Random(); 
int abc = rnd.nextInt(100); // +1 if you want 1-100, otherwise will be 0-99. 
+0

(通常讚賞對於反對票的解釋,特別是當不清楚OP是否更好地服務於更直接的解決方案)。 – 2013-03-31 16:43:46

+0

爲什麼?比另一個更隨意嗎? – user3932000 2017-04-15 04:38:29

+0

@ user3932000不是我所知道的 - 它更清楚。 – 2017-04-15 13:22:41

17

爲了您的代碼編譯,您需要將結果轉換爲int。

int abc = (int) (Math.random() * 100); 

但是,如果改用java.util.Random中類它有內置的方法爲你

Random random = new Random(); 
int abc = random.nextInt(100); 
0
int abc= (Math.random()*100);// wrong 

你港島線得到以下錯誤消息

Exception in thread "main" java.lang.Error: Unresolved compilation problem: Type mismatch: cannot convert from double to int

int abc= (int) (Math.random()*100);// add "(int)" data type 

,已知類型鑄造

如果真實結果是

int abc= (int) (Math.random()*1)=0.027475 

然後你會得到輸出爲「0」,因爲它是一個整數數據類型。

int abc= (int) (Math.random()*100)=0.02745 

輸出:2,因爲(100 * 0.02745 = 2.7456 ...等)

+0

(通過縮進四個空格或使用Ctrl-K快捷方式,將代碼格式化爲代碼通常很有幫助。) – 2014-11-30 18:07:11

-3
double i = 2+Math.random()*100; 
int j = (int)i; 
System.out.print(j); 
+0

此答案不添加任何值,因爲相同的答案已在3年前發佈。 – 2014-05-20 09:09:17

+0

除非你真的需要儲存'i',否則你最好馬上施放它,而不是將它儲存到它自己的一倍。 – user3932000 2017-04-15 04:40:12

0

您也可以使用這種方式越來越爲1和100之間的隨機數:

SecureRandom src=new SecureRandom(); 
int random=1 + src.nextInt(100); 
+1

歡迎在堆棧溢出!請查看[格式代碼](https://stackoverflow.com/help/formatting),以便它更具可讀性 – 2017-12-11 14:44:18

+0

一般來說,只有在需要密碼強的隨機數時才應使用SecureRandom,因爲它可能會阻止等待更多的熵。 – kodi 2017-12-11 14:55:56