栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

使用for,while,do...while计算100的阶乘(JAVA)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用for,while,do...while计算100的阶乘(JAVA)

使用for,while,do...while计算100的阶乘(JAVA)

前言代码


前言

起初我使用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)

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/713157.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号