实验三:分别用for、while和do-while循环语句以及递归方法计算n!,并输出算式
书写程序如下:
package 阶乘;
import java.util.Scanner;
import java.util.Scanner;
public class jiecheng {
public static void main(String[] args) {
//for循环
Scanner scanner=new Scanner(System.in);
System.out.print("请输入n的值:");
int n=scanner.nextInt();
int sum=1;
for(int i=1;i<=n;i++)
sum*=i;
System.out.println("用for循环输出阶乘的值:sum="+sum);
//while循环
System.out.print("请输入m的值:");
int m=scanner.nextInt();
int j=1;
int total=1;
while(j<=m)
{total*=j;
j++;}
System.out.println("用while循环输出阶乘的值:total="+total);
//do-while循环
System.out.print("请输入t的值:");
int t=scanner.nextInt();
int r=1;
int together=1;
do
{together*=r;
r++;}
while(r<=t);
System.out.println("用do-while循环输出阶乘的值:together="+together);
//递归方法
System.out.print("请输入x的值:");
int x=scanner.nextInt();
System.out.println("用递归方法输出阶乘的值:"+Recursion(x));
}
public static int Recursion(int y)
{
if(y==0) return 1;
else return y*Recursion(y-1);
}
}
//for循环
Scanner scanner=new Scanner(System.in);
System.out.print("请输入n的值:");
int n=scanner.nextInt();
int sum=1;
for(int i=1;i<=n;i++)
sum*=i;
System.out.println("用for循环输出阶乘的值:sum="+sum);
//while循环
System.out.print("请输入m的值:");
int m=scanner.nextInt();
int j=1;
int total=1;
while(j<=m)
{total*=j;
j++;}
System.out.println("用while循环输出阶乘的值:total="+total);
//do-while循环
System.out.print("请输入t的值:");
int t=scanner.nextInt();
int r=1;
int together=1;
do
{together*=r;
r++;}
while(r<=t);
System.out.println("用do-while循环输出阶乘的值:together="+together);
//递归方法
System.out.print("请输入x的值:");
int x=scanner.nextInt();
System.out.println("用递归方法输出阶乘的值:"+Recursion(x));
}
public static int Recursion(int y)
{
if(y==0) return 1;
else return y*Recursion(y-1);
}
}
实验结果如图:
实验心得:
1.实验时对于输入的程序段不太了解,经过网上查询,知道了怎么输入。
2.对于递归方法去求阶乘,感觉刚开始不太理解。
3.通过本次实验,学会了写一些基础的Java程序。