标签:style blog color 使用 java ar strong for 2014
大数值问题:
如果基本的整数(如:int、long)和浮点数的精度不狗满足需求时,那么就可以用java.math包中的两个类BigInteger(任意精度的整数)和BigDecimal(任意精度的浮点数).
这两个类可以实现人一次长度数字的数值
BigInteger a = BigInteger.valueOf(100);//把100转换为大数类型的整数使用valueOf()方法可以将普通的数值转化为大数
那么接下来,怎么用大数实现数值运算呢?
在JAVA中提供加法方法就是:
BigInteger sum = a.add(b);//c = a + b;BigInteger ji = a.multiply(b.add(BigInteger.valueOf(2)));//ji = a * ( b + 2)
注:
和C++不同,java只提供了字符串的连接,重载了+运算符,java没有提供运算符的重载功能,也没有给java程序员在自己的类中写运算符重载的机会。
计算组合数:
c = c.multiply(BigInteger.valueOf(n-i+1).divide(BigInteger.valueOf(i)));//(n-i+1)/i
/**
 描述:
 有n个球,一手可以抓m个,问有多少抓取方式,n以0输入结束
 思路:
 应用java.math包中的BigInteger类
 运用a.multiply(b)得出a*b积
 */
import java.math.BigInteger;
import java.util.Scanner;
public class Main 
{
	public static void main(String[] args)
	{
		Scanner in = new Scanner(System.in);
		
		int n = 1,m;//求C(m,n)的组合数
		while(0!=n)
		{
		n = in.nextInt();
		m = in.nextInt();
		BigInteger c = BigInteger.valueOf(1);
		for(int i = 1;i<=m;i++)
		{
c = c.multiply(BigInteger.valueOf(n-i+1)).divide(BigInteger.valueOf(i));
			
		}
		System.out.println(c);	
		}
		
		
	}
}//BigInteger add(BigInteger it)// 求和 //BigInteger subtract(BigInteger it) //求差 //BigInteger multiply(BigInteger it) //求积 //BigInteger divide(BigInteger it) //求商 //BigInteger mod(BigInteger it) //求模 //int compareTo (BigInteger it) //用于判断两个大数的大小,该大数与另一个大数it相等,返回0,小于,返回负,大于返回正 //static BigInteger.valueOf(long x) static BigInteger valueOf(long xx)//返回值 等于xx 的大整数
BigDecimal:
BigDecimal add(BigDecimal it)// 求和 BigDecimal subtract(BigDecimal it) //求差 BigDecimal multiply(BigDecimal it) //求积 BigDecimal mod(BigDecimal it) //求模
例外:
BigDecimal divide(BigDecimal it RoundingMode mode)5.0//四舍五入 想要计算必须要给出舍入方式,至于其他的舍入方式可以参考API文档 static BigDecimal valueOf(long x) //返回值等于x的大实数 static BigDecimal valueOf(long x,int k)//返回值为 x/(10的k次方)的大实数
标签:style blog color 使用 java ar strong for 2014
原文地址:http://blog.csdn.net/wjw0130/article/details/39458339