【发布时间】: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