简体   繁体   English

析因程序的输出

[英]Output of Factorial program

I am writing a program that should output the factorial of any number which is inputted by the user. 我正在编写一个程序,该程序应该输出用户输入的任何数字的阶乘。 The program correctly gives an output from 0 to 12 but if I enter 13, the output is 1932053504 but in my calculator, 13! 该程序正确地提供了从0到12的输出,但是如果我输入13,则输出为1932053504,但在我的计算器中为13! = 6227020800. = 6227020800。

Also in 32! 同样在32! and 33!, the output is negative (32! = -2147483648). 和33 !,输出为负(32!= -2147483648)。 Starting 34!, the output is zero(0). 从34!开始,输出为零(0)。

How can I fix this? 我怎样才能解决这个问题? I want the program to provide the correct output of any number entered by the user. 我希望程序提供用户输入的任何数字的正确输出。

import java.util.Scanner;
import java.io.*;
    public class one {

        public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter number: ");
        int val = in.nextInt();
        int factorial = 1;

        for (int i = 1; i <= val; i++) {
            factorial *= i;
        }
        System.out.println("The factorial of " + val + " is " + factorial);
   }
}

It exceeds the max value an integer can take 它超过了整数可以取的最大值

Max integer value:2147483647 最大数值:2147483647

Max long value: 9223372036854775807 最大值:9223372036854775807

Max double value: 7976931348623157^308 最大精度值:7976931348623157 ^ 308

Use long, double or BigInteger, which doesn't have upper boundaries 使用long,double或BigInteger(没有上限)

 public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter number: ");
        int val = in.nextInt();
        int factorial = 1;
        int i = 1;
        while (i <= val) {
            factorial = factorial * i;
            i++;
        }
        System.out.println("The factorial of " + val + " is " + factorial);
    }
}

That's how you'd do it with a while loop instead 那就是你用while循环来做的方式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM