【问题标题】:how to show the negative number factorial in this code如何在此代码中显示负数阶乘
【发布时间】:2019-03-24 05:57:51
【问题描述】:

我正在尝试制作一个计算器,但由于我的代码有些混乱,我无法继续。我试图对一个数字进行阶乘,如果它是一个正数,则没有错误,但每次我输入一个负数时,结果为 1,这是我的代码。

 import java.math.BigInteger;
import java.util.Scanner;

public class Factorial2 {

   public static void main(String[] args) {
       Scanner s = new Scanner(System.in);
       System.out.print("Enter a number: ");
       int n = s.nextInt();
       String fact = factorial(n);
       System.out.println("Factorial is " + fact);
   }

   public static String factorial(int n) {
       BigInteger fact = new BigInteger("1");
       for (int i = 1; i <= n; i++) {
           fact = fact.multiply(new BigInteger(i + ""));
       }
       return fact.toString();
   }
}

我已经尝试过创建 if 语句,但结果仍然是 1。我还想将负阶乘变成显示文本,而不是负阶乘的值

【问题讨论】:

  • 没有什么像 negative 阶乘。
  • 不是直接回答你的问题;但是BigInteger fact = BigInteger.ONE;fact = fact.multiply(BigInteger.valueOf(i));
  • 就像我需要伽玛运算,就像在科学计算器中,如果你输入一个负数,你可以得到它的阶乘
  • 负数阶乘:Factorials of real negative and imaginary numbers - A new perspective。引用:“1768 年,欧拉定义了 gamma 函数 Γ(z),并将阶乘的概念扩展到所有实负数,除了零和负整数。”
  • 或者,如果您希望我们告诉您如何计算负阶乘,您需要用清晰的数学术语向我们提供负阶乘的定义。

标签: java string algorithm math biginteger


【解决方案1】:

计算前需要验证输入,例如:

public static String factorial(int n) {
    if(n < 1) return "0";
    BigInteger fact = new BigInteger("1");
    for (int i = 1; i <= n; i++) {
        fact = fact.multiply(new BigInteger(i + ""));
    }
    return fact.toString();
}

当然你可以定义任何默认返回值或抛出错误:

if(n < 1) throw new RuntimeException("Input must be > 0");

【讨论】:

  • 如果我想返回负数阶乘的实数值怎么办?我应该在 return 语句中添加什么?
  • 根据维基百科的定义:en.wikipedia.org/wiki/Factorial#Definition 它仅适用于整数 >= 0,我不知道,你想做什么
猜你喜欢
  • 2018-01-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-04
  • 2018-06-24
  • 1970-01-01
相关资源
最近更新 更多