//搞定
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入不超过10的正整数:");
while(true){
int n = sc.nextInt();
if(n<1||n>10){
System.out.println("输入不合法,请输入不超过10的正整数:");
}else{
int s = add(n);
System.out.println("1到"+n+"的阶乘的和为:"+s);
break;
}
}
}
//计算1~n的阶乘的和
public static int add(int n){
int sum = 0;
while(n>0){
sum= sum+fac(n);
n--;
}
return sum;
}
//计算n的阶乘
public static int fac(int num){
if(num==1){
return 1;
}else{
return num*fac(num-1);
}
}
}
//计算n的阶乘还可以用循环可以写成这样:
public static int test(int num){
int result = 1;
while(num>0){
result = result*num;
num--;
}
return result;
}
那个好懂用哪个
递归调用求10以下的阶乘,给你个能直接运行的例子:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class digui {
public int sum = 0;
public String shuruStr;
public int shuruNum;
public void init() {
try {
do {
System.out.println("---请输入0-10之内的整数!---\t");
BufferedReader strin = new BufferedReader(new InputStreamReader(System.in));
shuruStr = strin.readLine();
shuruNum = Integer.parseInt(shuruStr);
} while (shuruNum > 10 || shuruNum <= 0 );
System.out.println("输入的数是:" + shuruNum);
diguiDy(shuruNum);
System.out.println("递归相乘的总和为:"+ sum);
} catch (IOException e) {
e.printStackTrace();
}
}
public int diguiDy(int var) {
if (var == 1) {
return sum += 1;
}
sum += (var - 1) * var;
diguiDy(var -1);
return sum;
}
public static void main(String[] args) {
new digui().init();
}
}
如果对回答满意,请点【采纳答案】,如果还有问题,请点【追问】
希望我的回答对您有所帮助,希望能采纳。
import java.util.*;
public class Text{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
int i = 1;
int j = 1;
int z = 0;
System.out.println("请输入一个数:");
int end = in.nextInt();
for(;i <= end;i ++)
{
j *= i;
z += j;
}
System.out.print("1!+"+"…+"+end+"!");
System.out.println("= "+z);
}
}
// int
// sum=0;