产生10个0~100之间的正整数
package com.bank.demo;
import java.util.Random;
public class TestDemo {
public static void main(String[] args) throws Exception {
Random rand = new Random(); // 实例化对象
for (int x = 0; x < 10; x++) {
System.out.print(rand.nextInt(101) + "、"); // 不大于101的正整数
}
}
}
观察四舍五入操作
package com.bank.demo;
public class TestDemo {
public static void main(String[] args) throws Exception {
System.out.println(Math.round(15.5)); // 计算结果:16
System.out.println(Math.round(15.51)); // 计算结果:16
System.out.println(Math.round(15.6)); // 计算结果:16
System.out.println(Math.round(15.2356)); // 计算结果:15
System.out.println(Math.round(-15.5)); // 计算结果:-15
System.out.println(Math.round(-15.51)); // 计算结果:-16
System.out.println(Math.round(-15.6)); // 计算结果:-16
}
}
BigInteger
package com.bank.demo;
import java.math.BigInteger;
public class TestDemo {
public static void main(String[] args) throws Exception {
BigInteger bigA = new BigInteger("234809234801"); // 大数字A
BigInteger bigB = new BigInteger("8939834789"); // 大数字B
System.out.println("加法结果:" + bigA.add(bigB));
System.out.println("减法结果:" + bigA.subtract(bigB));
System.out.println("乘法结果:" + bigA.multiply(bigB));
System.out.println("除法结果:" + bigA.divide(bigB));
BigInteger result[] = bigA.divideAndRemainder(bigB);
System.out.println("商:" + result[0] + ",余数:" + result[1]);
}
}
完成准确位的四舍五入操作
package com.bank.demo;
import java.math.BigDecimal;
class MyMath {
public static double round(double num, int scale) {
BigDecimal big = new BigDecimal(num); // 将数据封装在BigDecimal类中
BigDecimal result = big.divide(new BigDecimal(1), scale,
BigDecimal.ROUND_HALF_UP); // 除法计算
return result.doubleValue(); // Number类的方法
}
}
public class TestDemo {
public static void main(String[] args) throws Exception {
System.out.println(MyMath.round(15.5, 0)); // 计算结果:16
System.out.println(MyMath.round(-15.5, 0)); // 计算结果:-15
System.out.println(MyMath.round(168.98765, 2)); // 计算结果:168.99
}
}