2014-09-10 15 views
1

我寫了代碼,但沒有從double到int的轉換。如何使用Math類填充0到99之間的隨機數組?

public class Array { 
    public static void main(String[] args) { 
     int i; 
     int[] ar1 = new int[100]; 
     for(int i = 0; i < ar1.length; i++) { 
      ar1[i] = int(Math.random() * 100); 
      System.out.print(ar1[i] + " "); 
     } 
    } 
} 

如何糾正?

+0

AR1 [I] =((int)的的Math.random ()* 100); – StackFlowed 2014-09-10 14:47:30

+0

一個足夠智能的IDE(如Eclipse或IntelliJ)應該能夠自行糾正它:'(int)(Math.random()* 100);'。 – sp00m 2014-09-10 14:47:33

+0

不是一個答案,因爲您聲明必須使用Math,但Random類具有nextInt()函數來創建隨機整數 – LionC 2014-09-10 14:48:22

回答

4

應該是這樣

ar1[i] = (int)(Math.random() * 100); 

當你施放,施放類型應該在括號例如(cast type)value

6
ar1[i] = (int)(Math.random() * 100); 

轉換在Java中看起來像鑄於C.

+8

也被稱爲鑄造。 – 2014-09-10 14:47:36

3

試試這個:

package studing; 

public class Array { 
    public static void main(String[] args) { 
     Random r = new Random(); 
     int[] ar1 = new int[100]; 
     for(int i = 0; i < ar1.length; i++) { 
      ar1[i] = r.nextInt(100); 
      System.out.print(ar1[i] + " "); 
     } 
    } 
} 

爲什麼?

  1. 使用Math.random()可以返回1,這意味着Math.random()*100可以返回100,但OP要求最高99!使用nextInt(100)是唯一100,它只能從0返回值到99
  2. Math.random()不能返回-0.000001這將是一輪01.0000001不能返還應一輪1。所以你有更少的機會獲得099之間的所有數字。這樣,它不是真正的隨機,猜測「它不是099」比「它不是198」更真實。
  3. 此外,它不會通過你不需要的鑄造和數學操作繞道而行。
1

這是不實際使用java.lang.Math類,但在Java 8隨機陣列也可以以這種方式創建:

int[] random = new Random().ints(100, 0, 100).toArray();