计算:result = 1! + ... + 10!
一、使用for循环
public class Factorial
{
public static void main(String[] args)
{
long result = 0; long temp = 1;
for(int i=1; i<=10; i++)
{
temp *= i;
result += temp;
}
System.out.println("result=" + result);
}
}
二、使用递归调用
public class Recursive
{
public static void main(String[] args)
{
long result = 0;
for (int i = 1; i <= 10; i++)
{
long showResult = 0;
showResult = factorial(i);
System.out.println(i + "!=" + showResult);
result += showResult;
}
System.out.println("1!+...+10!=" + result);
}
public static long factorial(int number)
{
if (number == 1)
{
return 1;
}
else
{
return number * factorial(number - 1);
}
}
}