如何用JAVA编写 运用for循环,完成1*2*3…*10,并且改写成if和while,运用递归完成1*2*3…*10

求一个用java代码写出一个 用递归函数实现一个n的阶乘 要求n是从键盘上输入~

import java.util.Scanner;public class Factorial { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("请输入n:"); long n = Long.parseLong(sc.nextLine()); System.out.println(getFac(n)); } public static long getFac(long n){ if(n == 1){ return 1; } return getFac(n-1) * n; }}

不太明白你的问题。

public static void main(String[] args){
System.out.println(funFor(10));
System.out.println(funWhile(10));
System.out.println(funDigui(10));
}
private static int funFor(int n){//for循环
int s = 1;
for(int i=1;i<=n;i++){
s = s*i;
}
return s;
}
private static int funWhile(int n){//while循环
int s = 1;
int i = 1;
while(true){
s = s*i;
if(i==10){break;}
i++;
}
return s;
}
private static int funDigui(int n){//递归
if(n==1){return n;}else{
return n*funDigui(n-1);
}
}
希望你喜欢!

function int calc(int num)
int result = num;
if(num > 1){
result = num * calc(num - 1);
}
return result;

相关兴趣推荐

IT评价网,数码产品家用电器电子设备等点评来自于网友使用感受交流,不对其内容作任何保证

联系反馈
Copyright© IT评价网