gpt4 book ai didi

java - 阶乘程序的输出

转载 作者:行者123 更新时间:2023-11-30 03:16:16 24 4
gpt4 key购买 nike

我正在编写一个程序,该程序应该输出用户输入的任何数字的阶乘。程序正确地给出了从 0 到 12 的输出,但如果我输入 13,输出是 1932053504,但在我的计算器中,是 13! = 6227020800。

还有32!和 33!,输出为负 (32!= -2147483648)。从 34! 开始,输出为零 (0)。

我该如何解决这个问题?我希望程序能够正确输出用户输入的任何数字。

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);
}
}

最佳答案

它超出了整数可以取的最大值

最大整数值:2147483647

最大值:9223372036854775807

最大值:7976931348623157^308

使用 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);
}
}

这就是使用 while 循环的方法

关于java - 阶乘程序的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32523486/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com