簡體   English   中英

階乘程序未提供正確的輸出

[英]Factorial program not giving correct output

我編寫了以下程序,使用Java中的BigInteger計算n個整數的階乘,但結果始終為1。 錯誤在哪里?

import java.math.BigInteger;
import java.io.*;

class Factorial
{
    public static void main(String args[])
    {
        try
        {
            int key;
            BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
            BigInteger result=new BigInteger("1");
            //take the quantity of elements for which factorial is to be calculated
            int num=Integer.parseInt(br.readLine());

            while(num-->0)
            {
                //input the number for which factorial is to be calculated
                key=Integer.parseInt(br.readLine());
                while(key>0)
                {
                    System.out.println(key+""+result);
                    result.multiply(BigInteger.valueOf(key));
                    key--;
                }
                //again make the result back to 1 for next key element
                result=new BigInteger("1");
            }
        }catch(Exception e)
        {
            //do nothing
        }
    }
}

BigInteger是不可變的。 需要重新分配[BigIteger].mutlipy([BigInteger])的結果,以獲取所需的輸出,例如:

  result = result.multiply(BigInteger.valueOf(key));

在while循環中執行操作后,應打印結果。 看下面的修改代碼:

  key=Integer.parseInt(br.readLine());
  while(key>0){
       result = result.multiply(BigInteger.valueOf(key));
       key--;
  }
  System.out.println(key+" "+result);

暫無
暫無

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

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