因子Java程序 [英] Factorial Java Program

查看:164
本文介绍了因子Java程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用for循环在java中执行factorial程序。例如,我想接受用户输入,假设 10 ,然后乘以 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1 。我需要帮助构建 for 循环。下面的代码就是我到目前为止我不知道该去哪里。

I want to do a factorial program in java using a for loop. For example I want to take the user input, lets say 10, and then multiply 10*9*8*7*6*5*4*3*2*1. I need help constructing the for loop. The code below is all I have so far as I'm not sure where to go after.

import java.util.Scanner;
import java.lang.Math;
public class factorial {

    public static void main(String[] args) {
        int num;
        Scanner input = new Scanner(System.in);
        System.out.println("Enter a number: ");
        num = input.nextInt();
    }
}


推荐答案

尝试

public static void main(String[] args) {
    int num;
    int fact=1;
    Scanner input = new Scanner(System.in);
    System.out.println("Enter a number: ");
    num = input.nextInt();
    for (int i=2;i<=num; i++){
        fact=fact*i;
    }

    System.out.println("Factorial: "+fact);
}

正如@Marko Topolnik在评论中提到的,此代码适用于最多12个输入对于较大的输入,由于溢出会输出无穷大。

As @Marko Topolnik mentioned in comments this code will work for inputs up to 12. For larger inputs will output infinity due to overflow.

对于大于12的数字,你应该使用更高的数据类型,如 BigInteger

For numbers larger than 12 you should use higher data type like BigInteger

您可以尝试:

public static void main(String[] args) {
    BigInteger num;
    BigInteger fact = BigInteger.valueOf(1);
    Scanner input = new Scanner(System.in);
    System.out.println("Enter a number: ");
    num = input.nextBigInteger();
    for (int i = 2; i <= num; i++){
        fact = fact.multiply(BigInteger.valueOf(i));
    }
    System.out.println(fact);
}

这篇关于因子Java程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆