实验三:分别用for、while和do-while循环语句以及递归方法计算n!,并输出算式

实验三:分别用forwhiledo-while循环语句以及递归方法计算n!,并输出算式

//for循环语句求n

Public class jiecheng {

Public static void main (String[] args) {

Scanner = new Scanner(Sytem.in);

Int n = scanner.nextInt();

Int a =1;

For(int i=1;i<=n;i++){

a*=i;

}

System.out.printIn(a);

}

}

//while语句求n!

public class jiecheng {

 public static void main(String[] args) {

  Scanner in = new Scanner(System.in);

  int n;

  n=in.nextInt();

  int i=1,sum=1;

  while(i<=n)

  {

   sum=sum*i;

   i++;

  }

  System.out.printIn(sum);

 }

 

}

//do-while语句求n!

public class jiecheng {

public static void main(String[] args) {

int index = 1;

do {

System.out.println(index);

index = index + 1;

} while(index <= 10);

System.out.println("DONE.");

}

}

//递归语句求n! 

public class jiecheng {
public static void main(String args[]){

        Scanner input = new Scanner(System.in); //构建一个输入实例

        int n = input.nextInt();                //输入n的值

        System.out.println("The anwser of n! is " + jiecheng(n));      // n的阶乘的值为:jiecheng(n);   //用递归函数求解n的阶乘

    }

    public static int jiecheng(int n){         //阶乘求解函数

        if(n == 0){                             //判断传进来的n是否为0,若为零返回阶乘为1

            return 1;

        }

        return n*jiecheng(n-1);             //重新调用函数,继续判断n-1是否为零,

}                                          //若不为0则return值为n*(n-1)*jiecheng(n-1-1),直到n=0,跳出

 

心得:1.了解并掌握了循环结构fordo-shilewhile以及递归语句的用法。

           2.进一步熟悉了java语句的编写以及对eclipse的用法。

           3.在编写过程中应认真检查,不然出现字母出错都会导致程序大面积错误。

posted @ 2019-03-24 11:19  森.屿  阅读(1146)  评论(1编辑  收藏  举报