JAVA 基础知识学习22

数字处理类

目录

DecimalFormat类

public class DecimalFormatSimpleDemo {
    static public void simgleFormat(String pattern, double value) {
        DecimalFormat myFormat = new DecimalFormat(pattern);  //实例化DecimalFormat对象 
        String output =myFormat.format(value);          //将数字进行格式化
        System.out.println(value+"\t"+pattern+"\t"+output);
    }
    //使用applyPattern() 方法对数字进行格式化
    static public void UseApplyPatternMethodFormat(String pattern,double value){
        DecimalFormat myFormat =new DecimalFormat();   //实例化DecimalFormat 对象
        myFormat.applyPattern(pattern);    //调用applayPatten()方法设置格式化模板
        System.out.println(value+"\t"+pattern+"\t"+myFormat.format(value));
    }
    public static void main(String[] args) {
        simgleFormat("###,###,###", 123456.789);  //调用静态SimgleFormat()方法
        simgleFormat("0000000.###kg", 123456.789);   //数字后加上单位 
        //按照格式模板格式化数字,不存在的位以0显示
        simgleFormat("00000.000", 123.78);   
        //调用静态UserApplyPatternMethodFormat()方法
        UseApplyPatternMethodFormat("#.###%",0.789); //将数字转化为百分数形式
        UseApplyPatternMethodFormat("###.##", 123456.789);   //将小数点后格式化为两位
        UseApplyPatternMethodFormat("0.00\u2030", 0.789);    //将数字转化为千粉数形式


    }

}

Math 类

1.三角函数方法
在Math类中包含的三角函数方法如下:

l         public static double sin(double a):返回角的三角正弦。

l         public static double cos(double a):返回角的三角余弦。

l         public static double tan(double a):返回角的三角正切。

l         public static double asin(double a):返回一个值的反正弦。

l         public static double acos(double a):返回一个值的反余弦。

l         public static double atan(double a):返回一个值的反正切。

l         public static double toRadians(double angdeg):将角度转换为弧度。

l         public static double toDegrees(double angrad):将弧度转换为角度。

以上每个方法的参数和返回值都为double型的,将这些方法的参数的值设置为double型是有一定道理的,参数以弧度代替角度来实现,其中1度等于π/180弧度,所以180度可以使用π/2弧度来表示。除了可以获取角的正弦、余弦、正切、反正弦、反余弦、反正切之外,Math类还提供了角度和弧度相互转换的方法toRadians()、toDegrees()方法,但值得注意的是,角度与弧度的互换通常是不精确的。

例 在项目中创建TrigonometricFunction类,在类的主方法中调用Math类提供的各种数学运算方法,并输出运算结果。

public class TrigonometricFunction {

      public static void main(String[] args) {

            System.out.println("90度的正弦值:" + Math.sin(Math.PI / 2));        // 取90度的正弦

            System.out.println("0度的余弦值:" + Math.cos(0));                        // 取0度的余弦

            System.out.println("60度的正切值:" + Math.tan(Math.PI / 3));        // 取60度的正切

            // 取2的平方根与2商的反正弦

            System.out.println("2的平方根与2商的反弦值:" + Math.asin(Math.sqrt(2) / 2));

            // 取2的平方根与2商的反余弦

            System.out.println("2的平方根与2商的反余弦值:" + Math.acos(Math.sqrt(2) / 2));

            System.out.println("1的反正切值:" + Math.atan(1));                       // 取1的反正切

            System.out.println("120度的弧度值:" + Math.toRadians(120.0));     // 取120度的弧度值

            System.out.println("π/2的角度值:" + Math.toDegrees(Math.PI / 2)); // 取π/2的角度

      }

}

2.指数函数方法
在Math类中存在与指数相关的函数方法如下:

public static double exp(double a):用于获取e的a次方,即取eª。

public static double log(double a):用于取自然对数,即取㏑a的值。

public static double log10(double a):用于取底数为10的对数。

public static double sqrt(double a):用于取a的平方根,其中a的值不能为负值。

public static double cbrt(double a):用于取a的立方根。

public static double pow(double a,double b):用于取a的b次方。

指数运算包括求方根、取对数以及求n次方的运算,为了更好地理解这些运算函数方法的用法,请看下面的实例。

例 在项目中创建ExponentFunction类,在类的主方法中调用Math类中的方法实现指数函数的运算,并输出运算结果。

public class ExponentFunction {

      public static void main(String[] args) {

            System.out.println("e的平方值:" + Math.exp(2));                     // 取e的2次方

            System.out.println("以e为底2的对数值:" + Math.log(2));         // 取以e为底2的对数

            System.out.println("以10为底2的对数值:" + Math.log10(2));   // 取以10为底2的对数

            System.out.println("4的平方根值:" + Math.sqrt(4));                 // 取4的平方根

            System.out.println("8的立方根值:" + Math.cbrt(8));                // 取8的立方根

            System.out.println("2的2次方值:" + Math.pow(2, 2));              // 取2的2次方

      }

}

3.取整函数方法
在具体的问题中,取整操作使用也很普遍,所以Java在Math类中添加了数字取整方法,在Math类中主要包括以下几种取整方法:

public static double ceil(double a):返回大于等于参数的最小整数。
public static double floor(double a):返回小于等于参数的最大整数。
public static double rint(double a):返回与参数最接近的整数,如果两个同为整数都同样接近,则结果取偶数。
public static int round(float a):将参数加上1/2后返回与参数最近的整数。
public static long round(double a):将参数加上1/2后返回与参数最近的整数,然后强制转换为长整型。

下面用实例说明Math类中的取整方法的使用。
例 在项目中创建IntFunction类,在类的主方法中调用Math类中的方法实现取整函数的运算,并输出运算结果。

public class IntFunction {
      public static void main(String[] args) {
            //返回第一个大于等于参数的整数
            System.out.println("使用ceil()方法取整:"+Math.ceil(5.2));
            //返回第一个小于等于参数的整数
            System.out.println("使用floor()方法取整:"+Math.floor(2.5));   
            System.out.println("使用rint()方法取整:"+Math.rint(2.7));       //返回与参数最接近的整数
            //返回与参数最接近的整数
            System.out.println("使用rint()方法取整:"+Math.rint(2.5));              
            //将参数加上0.5后返回最接近的整数
            System.out.println("使用round()方法取整:"+Math.round(3.4f)); 
            //将参数加上0.5后返回最接近的整数,并将结果强制转换为长整型
            System.out.println("使用round()方法取整:"+Math.round(2.5));
      }
}

4.取最大值、最小值、绝对值函数方法
在程序中最常用的方法就是取最大值、最小值、绝对值等,在Math类中包括的这些操作的方法如下:

public static double max(double a,double b):取a与b之间的最大值。
public static int min(int a,int b):取a与b之间的最小值,参数为整型。
public static long min(long a,long b):取a与b之间的最小值,参数为长整型。
public static float min(float a,float b):取a与b之间的最小值,参数为浮点型。
public static double min(double a,double b):取a与b之间的最小值,参数为双精度型。
public static int abs(int a):返回整型参数的绝对值。
public static long abs(long a):返回长整型参数的绝对值。
public static float abs(float a) :返回浮点型参数的绝对值。
public static double abs(double a):返回双精度型的绝对值。

下面用实例说明上述方法的使用。
例 在项目中创建AnyFunction类,在类的主方法中调用Math类中的方法实现求两数的最大值、最小值和取绝对值运算,并输出运算结果。

public class AnyFunction {
      public static void main(String[] args) {
            System.out.println("4和8较大者:" + Math.max(4, 8));                 // 取两个参数的最大值
            System.out.println("4.4和4较小者:" + Math.min(4.4, 4));         // 取两个参数的最小值
            System.out.println("-7的绝对值:" + Math.abs(-7));                  // 取参数的绝对值
      }
}

Math.random() 方法

在Math类中存在一个random()方法,用于产生随机数字,这个方法默认生成大于等于0.0小于1.0的double型随机数,即0<=Math.random()<1.0,虽然Math.random()方法只可以产生0~1之间的double型数字,其实只要在Math.random()语句上稍加处理,就可以使用这个方法产生任意范围的随机数,如图1所示。

Math.random()方法

在项目中创建MathRondom类,在类中编写GetEvenNum()方法产生两数之间的随机数,并在主方法中输出这个随机数。

public class MathRondom {
      public static int GetEvenNum(double num1, double num2) {          // 定义产生偶数的方法
            int s = (int) num1 + (int) (Math.random() * (num2 - num1));    // 产生num1~num2之间的随机数
            if (s % 2 == 0) {                                                                    // 判断随机数是否为偶数
                  return s;                                                                          // 返回
            } else
                  // 如果是奇数
                  return s + 1;                                                                    // 将结果加一后返回
      }

      public static void main(String[] args) {
            System.out.println("任意一个2~32之间的偶数:" + GetEvenNum(2, 32));      // 调用产生随机数方法
      }
}

使用Math类的random()方法也可以随机生成字符,可以使用如下代码生成字符’a’~’z’之间的字符。
(char)(‘a’+Math.random()*(‘z’-‘a’+1));
通过上述表达式可以求出更多的随机字符,比如’A’~’Z’之间的随机,进而可以推理到求任意两个字符之间的随机字符,可以使用如下语句表示。
(char)(cha1+Math.random()*(cha2-cha1+1));
在这里可以将这个表达式设计为一个方法,参数设置为随机产生字符的上限与下限,为了说明这个方法,请看下面的实例。
例 在项目中创建MathRandomChar类,在类中编写GetRandomChar()方法产生随机字符,并在主方法中输出该字符。

public class MathRandomChar {
      public static char GetRandomChar(char cha1, char cha2) {            // 定义获取任意字符之间的随机字符
            return (char) (cha1 + Math.random() * (cha2 - cha1 + 1));
      }

      public static void main(String[] args) {
            System.out.println("任意小写字符" + GetRandomChar('a', 'z'));  // 获取a~z之间的随机字符
            System.out.println("任意大写字符" + GetRandomChar('A', 'Z')); // 获取A~Z之间的随机字符
            // 获取0~9之间的随机字符
            System.out.println("0到9任意数字字符" + GetRandomChar('0', '9'));
      }
}

Random 类

除了Math类中的random()方法可以获取随机数之外,在Java中又提供了一种可以获取随机数的方式,那就是java.util.Random类。可以通过实例化一个Random对象创建一个随机数生成器。
语法:

Random r=new Random();

r:Random对象。
以这种形式实例化对象时,Java编译器以系统当前时间作为随机数生成器的种子,因为每时每刻的时间不可能相同,所以产生的随机数将不同,但是如果运行速度太快,也会产生两次运行结果相同的随机数。
同时也可以在实例化Random类对象时,设置随机数生成器的种子。
语法:

Random r=new Random(seedValue);
l         r:Random类对象。
l         seedValue:随机数生成器的种子。

在Random类中提供获取各种数据类型随机数的方法,下面列举几个常用的方法。

public int nextInt():返回一个随机整数
public int nextInt(int n):返回大于等于0小于n随机整数
public long nextLong():返回一个随机长整型值
public boolean nextBoolean():返回一个随机布尔型值
public float nextFloat():返回一个随机浮点型值
public double nextDouble():返回一个随机双精度型值
public double nextGaussian():返回一个概率密度为高斯分布的双精度值

请看下面的实例。
例 在项目中创建RandomDemo类,在类的主方法中创建Random类的对象,使用该对象生成各种类型的随机数,并输出结果。

import java.util.Random;
public class RandomDemo {
      public static void main(String[] args) {
            Random r = new Random();           //实例化一个Random类
            // 随机产生一个整数
            System.out.println("随机产生一个整数:" + r.nextInt());
            // 随机产生一个大于等于0小于10的整数
            System.out.println("随机产生一个大于等于0小于10的整数:" + r.nextInt(10));
            // 随机产生一个布尔型的值
            System.out.println("随机产生一个布尔型的值:" + r.nextBoolean());
            // 随机产生一个双精度型的值
            System.out.println("随机产生一个双精度型的值:" + r.nextDouble());
            // 随机产生一个浮点型的值
            System.out.println("随机产生一个浮点型的值:" + r.nextFloat());
            // 随机产生一个概率密度为高斯分布的双精度值
            System.out.println("随机产生一个概率密度为高斯分布的双精度值:" + r.nextGaussian());
      }
}

示例: 微信红包算法采用的random 类

public static double getRandomMoney(RedPackage _redPackage) {
    // remainSize 剩余的红包数量
    // remainMoney 剩余的钱
    if (_redPackage.remainSize == 1) {
        _redPackage.remainSize--;
        return (double) Math.round(_redPackage.remainMoney * 100) / 100;
    }
    Random r     = new Random();
    double min   = 0.01; //
    double max   = _redPackage.remainMoney / _redPackage.remainSize * 2;
    double money = r.nextDouble() * max;
    money = money <= min ? 0.01: money;
    money = Math.floor(money * 100) / 100;
    _redPackage.remainSize--;
    _redPackage.remainMoney -= money;
    return money;
}

LeftMoneyPackage数据结构如下:

class RedPackage {
    int    remainSize;
    double remainMoney;
}

测试时初始化相关数据是:

static void init() {
    redPackage.remainSize  = 30;
    redPackage.remainMoney = 500;
}

BigInteger 类

BigInteger类型的数字范围较Integer类型的数字范围要大的多,Integer是int的包装类,int的最大值为231-1,如果要计算更大的数字,那么使用Integer数据类型无法实现,所以Java中提供了BigInteger类来处理更大的数字。BigInteger支持任意精度的整数,也就是说在运算中BigInteger类型可以准确的表示任何大小的整数值而不会丢失任何信息。
在BigInteger类中封装了多种操作,除了基本的加减乘除操作之外,还提供了绝对值、相反数、最大公约数,判断是否为质数等操作。
当使用BigInteger类时,可以实例化一个BigInteger对象,并自动调用相应构造函数。BigInteger类具有很多构造函数,但最直接的一种方式是参数以字符串形式代表要处理的数字。
语法如下:

public BigInteger(String val)
val:十进制字符串。

如果将2转换为BigInteger类型可以使用如下语句进行初始化操作。
BigInteger twoInstance=new BigInteger(“2”); //将十进制2转换为BigInteger形式
注意:在这里值得注意得是,参数2的双引号不能省略,因为参数是以字符串的形式存在的。
一旦创建了对象实例,就可以调用BigInteger类中的一些方法进行运算操作,包括基本的数字运算和位运算以及一些取相反、取绝对值等操作,以下代码列举了BigInteger类中常用的几种运算方法。

public BigInteger add(BigInteger val):做加法运算
public BigInteger subtract(BigInteger val):做减法运算
public BigInteger multiply(BigInteger val):做乘法运算
public BigInteger divide(BigInteger val):做除法运算
public BigInteger remainder(BigInteger val):做取余操作
public BigInteger[] divideAndRemainder(BigInteger val):用数组返回余数和商,结果数组中第一个值为商,第二个值为余数
public BigInteger pow(int exponent):进行取参数的exponent次方操作
public BigInteger negate():取相反数
public BigInteger shiftLeft(int n):将数字左移n位,如果n为负数,做右移操作
public BigInteger shiftRight(int n):将数字右移n位,如果n为负数,做左移操作
public BigInteger and(BigInteger val):做与操作
public BigInteger or(BigInteger val):做或操作
public int compareTo(BigInteger val):做数字比较操作
public boolean equals(Object x):当参数x是BigInteger类型的数字并数值相等时,返回true
public BigInteger min(BigInteger val):返回较小的数值
public BigInteger max(BigInteger val):返回较大的数值

现在可以了解BigInteger类的用法,下面我们在程序中使用这些方法。

例 在项目中创建BigIntegerDemo类,在类的主方法中创建BigInteger类的实例对象,调用该对象的各种方法实现大整数的加、减、乘、除和其他运算,并输出运算结果。

import java.math.BigInteger;
public class BigIntegerDemo {
      public static void main(String[] args) {
            BigInteger bigInstance=new BigInteger("4");                       //实例化一个大数字
            //取该大数字加2的操作
            System.out.println("加法操作:"+bigInstance.add(new BigInteger("2")));   
            //取该大数字减2的操作
            System.out.println("减法操作:"+bigInstance.subtract(new BigInteger("2")));
            //取该大数字乘以2的操作
            System.out.println("乘法操作:"+bigInstance.multiply(new BigInteger("2")));
            //取该大数字除以2的操作
            System.out.println("除法操作:"+bigInstance.divide(new BigInteger("2")));
            //取该大数字除以3的商
            System.out.println("取商:"+bigInstance.divideAndRemainder(new BigInteger("3"))[0]);
            //取该大数字除以3的余数
            System.out.println("取余数:"+bigInstance.divideAndRemainder(new BigInteger("3"))[1]);
            System.out.println("做2次方操作:"+bigInstance.pow(2));         //取该大数字的2次方
            System.out.println("取相反数操作:"+bigInstance.negate());      //取该大数字的相反数
      }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值