1、Math類
java.lang.Math類提供了常用的數學運算方法和兩個靜態常量E(自然對數的底數) 和PI(圓周率)
// 絕對值
System.out.println(Math.abs(-3.5)); // 3.5
// 最大值
System.out.println(Math.max(2.5, 90.5));// 90.5
// 亂數
int random = (int) (Math.random() * 10); // 生成一個0-10之間的亂數
// 四舍五入
System.out.println(Math.round(3.45)); // 3
System.out.println(Math.round(3.55)); // 4
// 向上取整(取大于當前數的最小整數)
System.out.println(Math.ceil(3.25)); // 4.0
// 向下取整(取小于當前數的最大整數)
System.out.println(Math.floor(3.25)); // 3.0
注:Math類方法很多,需要使用直接看API檔案即可,不需要全部掌握
2、Random類 -- java.util.Random類
//簡單介紹使用示例,不需要全部掌握,用到時候查下檔案即可
// 創建一個Random物件
Random rand=new Random();
for(int i=0; i<20; i++){
// 隨機生成20個隨機整數,并顯示
int num=rand.nextInt(10);// 回傳下一個偽亂數,整型的
System.out.println("第"+(i+1)+"個亂數是:"+num);
}
運行結果
第1個亂數是:4
第2個亂數是:8
第3個亂數是:5
第4個亂數是:3
第5個亂數是:1
第6個亂數是:1
第7個亂數是:1
第8個亂數是:8
第9個亂數是:8
第10個亂數是:7
第11個亂數是:5
第12個亂數是:7
第13個亂數是:9
第14個亂數是:4
第15個亂數是:0
第16個亂數是:5
第17個亂數是:0
第18個亂數是:3
第19個亂數是:8
第20個亂數是:9
3、生成指定范圍的亂數
(int)(a + Math.random() * b )——>[a,a + b)
//(int)(a + Math.random() * b )——[a,a + b)
//4~9-->(int)(4 + Math.random() * (10-4)) )——[4,10)
for (int i = 0; i < 20; i++) {
int RandomNum = 0;
//生成0~9的隨機整數
RandomNum = (int)( 4+Math.random() * (10-4));
System.out.println("生成的亂數為:"+ RandomNum);
}
運行結果
生成的亂數為:7
生成的亂數為:8
生成的亂數為:6
生成的亂數為:9
生成的亂數為:4
生成的亂數為:5
生成的亂數為:6
生成的亂數為:4
生成的亂數為:6
生成的亂數為:5
生成的亂數為:5
生成的亂數為:6
生成的亂數為:6
生成的亂數為:9
生成的亂數為:5
生成的亂數為:4
生成的亂數為:4
生成的亂數為:7
生成的亂數為:6
生成的亂數為:5
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/495549.html
標籤:其他
上一篇:DBPack 賦能 python 微服務協調分布式事務
下一篇:Spring-常用注解及作用
