import java.util.*;
// Algorithm and Java program to find a Factorial of a number using recursion
public class factorial {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter a number: ");
int n = input.nextInt();
System.out.println("The factorial of " + n + " is " + factorial(n));
}
private static double factorial (int n)
{
if (n == 1)
return 1;
else
return n * factorial(n - 1);
}
}
请输入一个数字:8 8的阶乘是40320.0
进程以退出代码0结束如何获得没有小数的整数?
您可以致电:获取int
价值或Double
价值:
Double n = new Double(40320.99);
int i = n.intValue();
您可以直接打印结果,无论它是int
还是Double
值数据类型。
更换
System.out.println("The factorial of " + n + " is " + factorial(n));
通过
System.out.println("The factorial of " + n + " is " + (int) factorial(n));
或(更好的方式)
更换
private static double factorial (int n)
通过
private static int factorial(int n)
说明
由于您的方法返回double
,您需要将其转换为int
,它没有小数位。你可能想看看Math
类的方法,如round()
,floor()
等。