按照你的要求编写的Java程序如下
import java.util.Scanner;
public class JieCheng {
public static long jieCheng(int n) {
long m=1;
for(int i=1;i<=n;i++){
m=m*i;
}
return m;
}
public static void main(String[] args) {
System.out.print("请输入一个数n:");
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
long sum=0;
for(int i=1;i<=n;i++){
sum=sum+jieCheng(i);
}
System.out.print("1!+2!+3!+...+"+n+"!的值为:"+sum);
}
}
运行结果
请输入一个数n:10
1!+2!+3!+...+10!的值为:4037913
public static void main(String[] args)
{
long sum=0;//因为数太大要定义成long类型
long n=1;
int i=1;
Scanner input =new Scanner(System.in);
int nb=input.next();
for (i=1; i<=nb ;i++ )
{
n*=i;//此处是计算每个项的阶乘
sum+=n;//此处是把每个项的阶乘数依次相加
}
System.out.println("所有阶乘数的和为:"+sum);
}
改下包名就能用
package com.yjiang;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
System.out.println("请输入一个数n:");
int n = new Scanner(System.in).nextInt();
String msg = "";
for(int i=1;i<=n;i++){
if(i == 1){
msg = "1!";
}else{
msg = msg + "+" + i + "!";
}
}
msg += "的值为:";
System.out.println(msg+Factorial(n));
System.out.println("Press any key to continue ...");
String wait = new Scanner(System.in).next();
main(null);
}
public static int Factorial(int m) {
if (m == 1) {
return 1;
}
int result = 1;
for(int i = 1; i <= m; i++) {
result *= i; }
return result + Factorial(m - 1); }
}