[英]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 。
方法:
以下是使用伽馬 function 計算分數階乘的簡單示例
分數的階乘計算示例:
有用的 url 用於伽瑪 Function
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.