编写一个JAVA程序,从键盘输入一个数,计算阶乘.如输入:3,则输出1!+2!+3!

2024-11-15 15:02:35
推荐回答(4个)
回答1:

package com;
import java.util.Scanner;
public class Help {
public static void main(String[] args) {
System.out.println("请输入一个一个整数:");
Scanner input=new Scanner(System.in);
int a=input.nextInt();
int result=jie(a);
System.out.println("结果是:"+result);
}

private static int jie(int n){
int result=1;
if(n==0){
return 1;
}else {
for(int i=1;i<=n;i++){
result*=i;
}
return result;
}
}
}

回答2:

import java.util.Scanner;
 
publicclass P4_2 {
      publicstaticvoid main(String args[]){
            Scanner c = new Scanner(System.in);
            int in=0;
            try{
                  in = c.nextInt();
            }catch (Exception e) {
            }
            int sum = 0;
            int currentItem = 1;
            if(in<=0){
                  System.out.println("请输入正整数!");
            }else{
                  for (int i = 1; i <= in; i++) {
                        currentItem =currentItem*i;
                        sum = sum+currentItem;
                  }
                  System.out.println(sum);
            }
    }
}

回答3:

Scanner scanner = new Scanner(System.in);
System.out.print("输入整数:");
String strIn = scanner.next();
double m = 0;
int in = 0;
if (strIn.matches("[0-9]+")) {
in = Integer.parseInt(strIn);
for (int i = 1; i <= in; i++) {
int tool = 1;
for (int j = 1; j <= i; j++) {
tool *= j;
}
m += tool;
}
System.out.println(m);
} else {
System.out.println("输入错误");
}

回答4:

package com.chen;

import java.util.Scanner;

public class jiecheng {

static int a;
static int e=0;
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
a=sc.nextInt();
for(int i=1;i<=a;i++){
int c =Jie(i);
e+=c;
}

System.out.println(e);
}
public static int Jie(int n){
if(n==1){
return 1;
}

return n*Jie(n-1);
}

临时瞎写的 希望能帮上你~