递归 - 如何获得没有小数的整数

问题描述 投票:0回答:2
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结束如何获得没有小数的整数?

java recursion double
2个回答
1
投票

您可以致电:获取int价值或Double价值:

Double n = new Double(40320.99);
int i = n.intValue();

您可以直接打印结果,无论它是int还是Double值数据类型。


0
投票

更换

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()等。

© www.soinside.com 2019 - 2024. All rights reserved.