計算兩個整數數之間的隨機整數---2

    /**
     * @Description:輸出某兩個整數之間的一個隨機數
     **/
    public static int randNumBetweenTwoInt(int n, int m){
        //首先判斷m,n之間是否有整數
        if((Math.abs(m-n)) > 1){
            //生成一個範圍在0 ~ |m-n|之間的數,m,n的大小不確定故取兩者的絕對值
            //使用Math.abs()獲取m-n的絕對值
            int rand = 0;
            rand = (int)(Math.random()*(Math.abs(m - n) + 1));
            int randNew = rand + Math.min(n,m);
            return randNew;
        }else{
            System.out.println(n+" ~ "+m+" 之間不存在其他整數!");
            return 0;
        }
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章