求Sn=1!+2!+3!+4!+5!+…+n!之值,其中n是一个数字(n不超过20)。`
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int temp = 1;
int sum = 0;
for(int j=1;j<=n;j++)
{
temp *= j;
sum += temp;
}
System.out.print(sum);
}
}
如果觉得有点绕,debug跟踪一下变量就很清楚了。
但是这样写oj是显示正确率不是百分百的,为什么呢,原来是因为到了后面sum太大了超出int能表示的范围就出错了,所以要用长整型变量声明。
Java中声明长整型变量语句:
long a = 10000000L;
所以,这样写才能正确ac。就是改一下变量声明类型。
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
long temp = 1L;
long sum = 0L;
for(int j=1;j<=n;j++)
{
temp *= j;
sum += temp;
}
System.out.print(sum);
}
}