簡體   English   中英

如何計算Java中的十進制數的階乘?

[英]How to Calculate the factorial of a decimal number in Java?

我做了一個 function 來計算一個數字的階乘,但是當我寫一個十進制數字或一個字符時,“迷你應用程序”不起作用。 我如何計算小數的階乘並在用戶寫入字符時向用戶發送消息錯誤。?

 private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
     // BOTON CALCULAR

     String valortextfield = jTextField1.getText();
     int numero = Integer.parseInt(valortextfield);
     Metodos metod = new Metodos();

     BigInteger resultado = metod.factorial(numero);
     String valorAmostrar= resultado.toString();

     jTextArea1.setText(valorAmostrar);

    }    

方法:

public class Metodos {

    public BigInteger factorial (int numero ){
    if ((numero < 0)||(numero >50)) {

        return BigInteger.ZERO;


    } else if (numero==0){

        return BigInteger.ONE;

    } else {
        return BigInteger.valueOf(numero).multiply(factorial(numero-1));
    }
}

謝謝。

parseInt()調用周圍放置一個try / catch塊,然后查找NumberFormatException

String valortextfield = jTextField1.getText();
try
{
   int numero = Integer.parseInt(valortextfield);
   Metodos metod = new Metodos();

   BigInteger resultado = metod.factorial(numero);
   String valorAmostrar= resultado.toString();

   jTextArea1.setText(valorAmostrar);
}
catch (NumberFormatException e)
{
   // Show an error message here or whatever is appropriate
}

這不僅將捕獲“ 123.45”之類的數字,還將捕獲其他非數字輸入。

使用掃描儀

java.util.Scanner scanner = new  Scanner(System.in);
while (!scanner.hasNextInt()) 
  scanner.next();
System.out.println(scanner.next());

看到這個 這是一個近似值

您的階乘方法僅適用於integer 數字,但對於分數值有不同的方法,您必須使用gamma function

方法:

  • 首先收集輸入值
  • 驗證輸入,會出現以下三個條件之一:
    • 非數字輸入:顯示錯誤信息。
    • integer 編號:按照您在階乘方法中定義的相同方式填充階乘。
    • 分數:使用gamma function填充階乘,如下所述-

以下是使用伽馬 function 計算分數階乘的簡單示例

分數的階乘計算示例:

  • 公式

在此處輸入圖像描述

  • 這里取小數1.5! 作為示例並應用上述公式:

在此處輸入圖像描述

有用的 url 用於伽瑪 Function

暫無
暫無

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

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