簡體   English   中英

析因程序的輸出

[英]Output of Factorial program

我正在編寫一個程序,該程序應該輸出用戶輸入的任何數字的階乘。 該程序正確地提供了從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循環來做的方式

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM