试用范围:当对数据处理时,最大的long型不能装下,这时候就需要采用大数BigInteger来解决
简单的例子:
package cn.hncu.BigNUM;
import java.math.BigInteger;
public class bigIntegerdemo {
public static void main(String[] args) {
BigInteger sum=jc(100);//计算100的阶乘是很大的数,long是超范围的,所以采用Java 中的大数处理,BigInteger
System.out.println(sum);
}
private static BigInteger jc(int n) {
BigInteger s=BigInteger.valueOf(1);//必须先变成bigInteger类型的才能进行运算
for(int i=1;i<=n;i++){
s=s.multiply(BigInteger.valueOf(i));//BigInteger的函数乘法也要用到函数
}
return s;
}
}
若是采用double 值来操作,就会可能出现0.9999等一些近似值
部分简单代码
package cn.hncu.BigNUM;
import java.math.BigDecimal;
public class BigDecimal1 {
//高精度数处理
public static void main(String[] args) {
double sum=0;
for(int i=0;i<10;i++){
sum=sum+0.1;
}//0.9999999999999999
System.out.println(sum);//这样的结果,是按着科学计算法来算,如double 四位,用二进制来表示,因为不可能完全能够表示,所以去了近似值
add();
}
private static void add() {
BigDecimal be =new BigDecimal(0);
for(int i=0;i<10;i++){
be=be.add(new BigDecimal(0.1));//变成高精度后,会运算精准
}
System.out.println(be.doubleValue());//1.0
}
}