繁体   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