package com.hx.test;public class Test {
    public Test() {
    }    public int f(int n) {
        if (n == 0) {
            return 1;
        }
        return n * f(n - 1);
    }    public static void main(String[] args) {
        Test test = new Test();
        int result = test.f(20);
        System.out.println("result = " + result);
    }
}为什么结果是:result = -2102132736
是一个负数
如果将test.f(20)中的20改为10的话,运算的结果是正数

解决方案 »

  1.   

    超int的范围啦.....
    你把result改成long
    f()的返回值改成long试试
      

  2.   

    把程序段中所有的 int 全改为 long,最大可以支持到 20 的阶乘。想再计算更大的阶乘的话需要使用 BigInteger 类了,BigInteger 可以精确计算任意位数的数值,仅受计算机内存限制。下面是采用 BigInteger 的实现,可以参考一下。import java.math.BigInteger;public class Test2 {  public static BigInteger factor(BigInteger n) {
        if (n.equals(new BigInteger("0"))) {
          return new BigInteger("1");
        }
        return n.multiply(factor(n.subtract(new BigInteger("1"))));
      }
      
      public static void main(String[] args) {
        String s = "200";
        BigInteger big = factor(new BigInteger(s));
        System.out.println(s + "! = " + big.toString());
        System.out.println(s + "! 共有 " + big.toString().length() + " 位");
      }
    }
      

  3.   


    public class Test
    {
    public long f(long n)
    {
    if (n == 0)
    {
    return 1;
    }
    return n * f(n - 1);
    } public static void main(String[] args)
    {
    Test test = new Test();

    long result = test.f(20);

    System.out.println("result = " + result);
    }
    }
      

  4.   

    超出了int的范围了,具体为什么是这个数呢,
    是因为求的是int可表示最大数的模