前言代码
前言
起初我使用long来记录阶乘的结果,但发现结果为0,后来debug发现long的位数完全不够用,然后搜索后发现java里有一个叫BigInteger的类,这个类可以记录超大的值,于是我使用这个尝试计算100的阶乘。
代码package hust.limul.c4; import java.math.BigInteger; public class Main { public static void main(String[] args) { // write your code here //long s = 1; long不够大 BigInteger s = new BigInteger("1"); //构造函数BigInteger(String val) //使用for计算100的阶乘 for(int i = 1;i <= 100;i++) s = s.multiply(BigInteger.valueOf(i)); //乘法函数BigInteger.multiply(BigInteger val),使用BigInteger.valueOf(long val)把long转为BigInteger,这里i有隐式转变为long System.out.println(s); //使用while计算100的阶乘 s = BigInteger.valueOf(1); //BigInteger.valueOf(long val)将long转为BigInteger int i = 1; while(i <= 100) s = s.multiply(BigInteger.valueOf(i++)); System.out.println(s); //使用do...while计算100的阶乘 s = BigInteger.valueOf(1); i = 1; do s = s.multiply(BigInteger.valueOf(i++)); while(i <= 100); System.out.println(s); } }
BigInteger构造函数:BigInteger(String val)BigInteger乘法函数:BigInteger.multiply(BigInteger val)long→BigInteger:BigInteger.valueOf(long val)
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)