您的位置 首页 Java

Math.random()随机整数错误用法

public class Ans3_4_page93{
    public static void main(String[] args){
        //错误用法 导致month的值等于0,永不等于12,可以把12改成13
        //可用于抽奖排除中奖号码
        int month = (int)(Math.random() * 12);

        switch (month) {
            case 1:
                System.out.println("January");
                break;
            case 2:
                System.out.println("February");
                break;
            case 3:
                System.out.println("March");
                break;
            case 4:
                System.out.println("April");
                break;
            case 5:
                System.out.println("May");
                break;
            case 6:
                System.out.println("June");
                break;
            case 7:
                System.out.println("July");
                break;
            case 8:
                System.out.println("August");
                break;
            case 9:
                System.out.println("September");
                break;
            case 10:
                System.out.println("October");
                break;
            case 11:
                System.out.println("November");
                break;
            case 12:
                System.out.println("December");
                break;
        }
    }
}

public class Demo {
    public static void main(String[] args) {
        while (true) {
            double number0 = Math.random();
            double number1 = number0 * 12;
            int number = (int) (number1);
            System.out.println("原始数      " + number0);
            System.out.println("原始数乘以12 " + number1);
            System.out.println(number);
            System.out.println("---------------------");
        }
    }
    }

原始数      3.111564749883611E-4
原始数乘以12 0.003733877699860333
0
---------------------
原始数      0.07859998705330462
原始数乘以12 0.9431998446396554
0
---------------------

Process finished with exit code -1
未注明转载的文章均为原创,并采用 CC BY-NC-SA 4.0 授权协议,转载请注明来源:https://cn.fankuiba.com/262.html

作者: 博主

发表评论

电子邮件地址不会被公开。 必填项已用*标注

返回顶部