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的话,运算的结果是正数
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的话,运算的结果是正数
你把result改成long
f()的返回值改成long试试
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() + " 位");
}
}
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);
}
}
是因为求的是int可表示最大数的模