Skip to content

生成随机数

知识点

  1. 方法:random
  2. 参数:无
  3. 返回值:[ 0, 1 ) 随机数,包括 0 不包括 1

代码演示

需求:返回 0~10 之间的随机整数,包含 0 和 10

java
public class Index {
    public static void main(String[] args) {
        double ran = Math.random();
        System.out.println((int)(11 * ran));
    }
}

返回 n 的 m 次方

知识点

  1. 方法:pow
  2. 参数:参数1 - n,参数2 - m
  3. 注意:pow 方法返回值是一个 double 类型的数据。

代码实现

需求:计算并输出 2 的 1~5 次方。

java
public class Index {
    public static void main(String[] args) {
        int i = 1;
        while (i < 6) {
            System.out.println("i = " + i + " --- " + Math.pow(2,i));
            i++;
        }
    }
}

基于 MIT 许可发布