JavaSE學習筆記 - 數字類、隨機數
阿新 • • 發佈:2020-08-27
BigInteger
import java.math.BigInteger; public class Main { public static void main(String[] args) { //加 BigInteger ans = BigInteger.ONE; for (int i = 0; i < 1000; i++) { ans = ans.add(BigInteger.valueOf(i)); } System.out.println(ans); //減 ans = BigInteger.ZERO; for (int i = 0; i < 1000; i++) { ans = ans.subtract(BigInteger.valueOf(i)); } System.out.println(ans); //乘 ans = BigInteger.ONE; for (int i = 1; i < 1000; i++) { ans = ans.multiply(BigInteger.valueOf(i)); } System.out.println(ans); System.out.println(ans.gcd(BigInteger.ONE)); //gcd System.out.println(ans.mod(BigInteger.valueOf(10))); //取模 System.out.println(ans.compareTo(BigInteger.ONE)); //比較 ans = BigInteger.ONE; //除 for (int i = 1; i < 1000; i++) { ans = ans.divide(BigInteger.valueOf(i)); } System.out.println(ans); } }
DecimalFormat
public class Main { public static void main(String[] args) { DecimalFormat df = new DecimalFormat("###,###.##"); System.out.println(df.format(333333.44444));//333,333.44 df = new DecimalFormat("###,###.0000"); System.out.println(df.format(11111.11));//11,111.1100 df = new DecimalFormat("###.##"); System.out.println(df.format(1111.115));//1111.12 } }
BigDecimal
public class Main { public static void main(String[] args) { BigDecimal ans = BigDecimal.ONE; ans = ans.add(BigDecimal.valueOf(555.55)); System.out.println(ans);//556.55 ans = ans.subtract(BigDecimal.valueOf(555.55)); System.out.println(ans);//1.00 ans = ans.multiply(BigDecimal.valueOf(555.55)); System.out.println(ans);//555.5500 ans = ans.divide(BigDecimal.valueOf(555.55)); System.out.println(ans);//1.00 //如果是無限迴圈小數可以選擇四捨五入的方式進行取捨 ans = ans.divide(BigDecimal.valueOf(3), BigDecimal.ROUND_HALF_UP); System.out.println(ans); } }
Random
public class Main {
public static void main(String[] args) {
//如果隨機種子被固定,那麼每次生成隨機數都是一樣的數
//Random random = new Random(0);
Random random = new Random();
int num = random.nextInt(); //int範圍內生成一個隨機數
System.out.println(num);//-1155484576
for (int i = 0; i < 10; i++) {
System.out.print(random.nextInt(100) + " "); //[1, 100);
}
System.out.println();//48 29 47 15 53 91 61 19 54 77
double num1 = random.nextDouble();
System.out.println(num1); //[0, 1.0)
for (int i = 0; i < 10; i++) {
System.out.print(random.nextDouble() * 100 + " "); //[0, 100.0)
}
System.out.println();
//45.89635388212344 31.801944345473622 92.9140933009556 98.09388893069377 1.6510586300813146 36.87360429525213 30.092352127985432 51.19119225676931 10.159602362633658 53.97847957721588
Boolean flag = random.nextBoolean();
System.out.println(flag);
for (int i = 0; i < 10; i++) {
System.out.print(random.nextBoolean() + " ");
}
System.out.println();
}
}