簡體   English   中英

我不明白這部分。 誰能解釋這個循環和 math.random*2 是如何工作的

[英]I do not understand this part. Can anyone explain how this loop and math.random*2 is working

幫助我理解這段代碼

公共 class 練習 12 {

公共 static 無效主(字符串 [] 參數){

    Scanner in = new Scanner(System.in);
    System.out.print("Input a number: ");
    int n = in.nextInt();
    printMatrix(n);
}

公共 static 無效 printMatrix(int n) {

    for(int i = 0; i < n; i++) {
        for(int j = 0; j < n; j++) {
            System.out.printin((int)(Math.random() * 2) + " ");
        }
        System.out.println();
    }
}

}

Math.random()返回一個介於0.0 (包括)和1.0 (不包括)之間的數字。

因此(Math.random() * 2)是介於0.0 (含)和2.0 (不含)之間的數字。

因此(int)(Math.random() * 2)01

  • 如果(Math.random() * 2) == 0.xxxx ,將其轉換為int會導致0
  • 如果(Math.random() * 2) == 1.xxxx ,將其轉換為int會導致1

因此,此代碼打印 n * n 01元素的矩陣。

暫無
暫無

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

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