求N的阶乘。

package book;
import java.util.Scanner;//导入数据包,为实现N的输入
public class JangCai {
public static void main(String args[]){
System.out.println("for循环实现n的阶乘");
Scanner su=new Scanner(System.in);
System.out.println("n的值为:");
int n=su.nextInt();
int num=1;
for(int j=1;j<=n;j++){
num=num*j;
}
System.out.println(n+"的阶乘为"+num);
System.out.println("while实现n的阶乘!");
int j=num=1;
while(j<n){
j=j+1;
num*=j;
}
System.out.println(n+"的阶乘为"+num);
System.out.println("do-while实现n的阶乘!");
do{
num*=j;
j+=1;
}while(j<n);
System.out.println(n+"的阶乘值为:"+num);
System.out.println("利用递归方法实现N的阶乘!");
System.out.println("递归方法:"+ShiXian(n));
}
public static int ShiXian(int n){
if(n==0)
return 1;
else
return n*ShiXian(n-1);
}
}

程序运行结果:

第一种,利用for循环实现n的阶乘

请输入n的值:10
10的阶乘值为3628800
while实现n的阶乘!
10的阶乘值为3628800
do-while实现n的阶乘!
10的阶乘值为:36288000
利用递归方法实现N的阶乘!
递归方法:3628800

猜你喜欢

转载自www.cnblogs.com/jcdz/p/10597493.html