[英]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)
是0
或1
:
(Math.random() * 2) == 0.xxxx
,將其轉換為int
會導致0
(Math.random() * 2) == 1.xxxx
,將其轉換為int
會導致1
因此,此代碼打印 n * n 0
或1
元素的矩陣。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.