为什么我的递归程序打印一个负数? [英] Why does my recursion program print a negative number?

查看:185
本文介绍了为什么我的递归程序打印一个负数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于某些原因,我的代码在运行某些数字时会打印出负数(17).应该找到一个数字的阶乘并打印出来,但是要清楚地表明这是没有发生的.

My code for whatever reason is printing out a negative number when i run it with certain numbers(17). It is supposed to find the factorial of a number and print it out however clearly that isn't happening.

package recursion;

public class recursion_1 {

public static void main(String[] args) {
int x = factorial(17);
System.out.println(x);
}
public static int factorial(int N) { 
       if (N == 1) return 1; 
       return N * factorial(N-1); 
    }   
}

推荐答案

您遇到整数溢出.

factorial(17)是3.5568743e + 14,远远超出了int的范围.当整数运算溢出时,其结果可能为负.例如:

factorial(17) is 3.5568743e+14, which is well beyond the bounds of int. When an integer operation overflows, it can end up negative. For example:

int x = Integer.MAX_VALUE;
x++;
System.out.println(x); // Very large negative number

在您的情况下,您会溢出数次-即使结果是肯定的,它仍然不是正确.

In your case, you'll have overflowed several times - even if the result were positive, it still wouldn't be right.

如果您需要[-2 63 ,2 63 -1]范围内的整数,则可以使用long代替int.如果要任意大的整数,请改用BigInteger.例如:

If you need integers in the range of [-263, 263-1] you can use long instead of int. If you want arbitrarily large integers, use BigInteger instead. For example:

// Note rename of parameter to follow Java conventions
public static BigInteger factorial(int n) {
    return factorial(BigInteger.valueOf(n));
}

public static BigInteger factorial(BigInteger n) {
    if (n.equals(BigInteger.ONE)) {
        return BigInteger.ONE;
    }
    return n.multiply(n.subtract(BigInteger.ONE));
}

这篇关于为什么我的递归程序打印一个负数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆