Java学习路线-18:数字操作类Math、Random、BigInteger、BigDecimal
发布日期:2021-07-01 06:08:07 浏览次数:2 分类:技术文章

本文共 2998 字,大约阅读时间需要 9 分钟。

第8 章 : 数字操作类

33 Math数学计算类

Math提供的方法都是static方法,都是基本数学公式

Math.abs(-10) // 10Math.max(10, 1) // 10Math.pow(10, 2) //100.0Math.sqrt(9) //3.0Math.round(10.4) // 10Math.round(10.5) // 11
class MathUtil {
private MathUtil() {
} // 自定义保留位数 public static double round(double num, int scale) {
return Math.round(num * Math.pow(10, scale)) / Math.pow(10, scale); }}class Demo {
public static void main(String[] args) {
System.out.println(MathUtil.round(10.98766, 2)); // 10.99 }}

34 Random随机数生成类

import java.util.Random;class Demo {
public static void main(String[] args) {
Random random = new Random(); // 产生随机数范围[0, 10) System.out.println(random.nextInt(10)); }}

彩票号码生成示例

import java.util.Random;/** * 随机示例 * 36 选 7 */class Demo {
public static int[] getCodeList(){
int[] data = new int[7]; int foot = 0; Random random = new Random(); while (foot<7){
int code = random.nextInt(37); if(isUse(code, data)){
data[foot++] = code; } } return data; } // 检查号码是否可以使用,不能为0,不能重复 public static boolean isUse(int code, int[] temp){
if(code == 0){
return false; } for(int x : temp){
if(code == x){
return false; } } return true; } public static void main(String[] args) {
int[] data = getCodeList(); for(int x : data){
System.out.print(x + ", "); } // 15, 19, 9, 11, 33, 2, 21, }}

35 大数字处理类

可以使用String保存,不过操作麻烦

继承体系

Object    -Number        -Integer        -Byte        -Long        -Short        -Float        -Double        -BigInteger        -BigDecimal    -Boolean    -Character

BigInteger 和 BigDecimal使用方法基本相似

过大的数据也会影响程序性能,优先使用基础数据类型

减法运算

import java.math.BigInteger;class Demo{
public static void main(String[] args) {
BigInteger big1 = new BigInteger("98960973126687599871"); BigInteger big2 = new BigInteger("98960973126687599872"); System.out.println(big2.subtract(big1)); // 1 }}

求余运算

import java.math.BigInteger;class Demo{
public static void main(String[] args) {
BigInteger big1 = new BigInteger("1001"); BigInteger big2 = new BigInteger("10"); BigInteger[] ret = big1.divideAndRemainder(big2); System.out.println(ret[0] + ", " + ret[1]); // 100, 1 }}

使用BigDecimal实现四舍五入进位

import java.math.BigDecimal;import java.math.RoundingMode;class MathUtil {
private MathUtil() {
} // 自定义保留位数 public static double round(double num, int scale) {
return new BigDecimal(num).divide( new BigDecimal(1.0), scale, RoundingMode.HALF_UP).doubleValue(); }}class Demo {
public static void main(String[] args) {
System.out.println(MathUtil.round(10.98766, 2)); // 10.99 }}

Math使用的是基本数据类型,性能高于大数据处理类

转载地址:https://pengshiyu.blog.csdn.net/article/details/103134228 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:Java学习路线-19:日期操作类Date、SimpleDateFormat
下一篇:Java学习路线-17:Java基础类库StringBuffer、AutoCloseable、Runtime、System

发表评论

最新留言

网站不错 人气很旺了 加油
[***.192.178.218]2024年05月05日 17时05分44秒