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.i,我还想将否定阶乘转换为显示文本,而不是否定阶乘的值
答案 0 :(得分: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");