简体   繁体   English

如何在此代码中显示负数阶乘

[英]how to show the negative number factorial in this code

im trying to make a calculator and im was unable to continue because of some confusion in my codes.我正在尝试制作一个计算器,但由于我的代码有些混乱,我无法继续。 i was trying to make a factorial of a number, if its a positive number there is no error but every time i input a negative number it results to 1, here is my code .我试图对一个数字进行阶乘,如果它是一个正数,则没有错误,但每次我输入一个负数时,结果为 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();
   }
}

i already tried making if statements but still it results to 1.i also want to make the negative factorial into a display text not the value of the negative factorial我已经尝试过进行 if 语句,但结果仍然是 1.我还想将负阶乘变成显示文本,而不是负阶乘的值

You need to validate the input before the calculation, example:您需要在计算之前验证输入,例如:

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();
}

Of course you can define any default return value or throw an error:当然,您可以定义任何默认返回值或抛出错误:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM