欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java的for循环 、do-while、while三种方法求n的阶乘

程序员文章站 2024-03-15 18:50:18
...

Java的for循环 、do-while、while三种方法求n的阶乘

 

for循环:

package com.study;
import java.util.Scanner;
public class CountFor {
    public static void main(String[] args) {
        int x;
        int sum=1;
        System.out.println("请输入数字n:");
        Scanner  in=new Scanner(System.in);
        int i=in.nextInt();
        String s = " ! =";
        for(x=1;x<=i;x++){
            sum=sum*x;
            if (x<i){
                s = s + x+ '*' ;
            }
            else{
                s = s  + x + "=" + sum;
            }
        }
        System.out.println(i+s);
    }
}

 

do-while:

package com.study;
import java.util.Scanner;
public class CountDo {
    public static void main(String[] args) {
        int x=1;
        int sum=1;
        System.out.println("请输入数字n:");
        Scanner in=new Scanner(System.in);
        int i=in.nextInt();
        String s = " ! =";
        do {
            sum=sum*x;
            if (x<i){
                s = s + '*' + x;
            }
            else{
                s = s +"*" + x + "=" + sum;
            }
            x++;
        }while(x<=i);
        System.out.println(i+s);
    }
}

 

while:

package com.study;
import java.util.Scanner;
public class CountWhile {
    public static void main(String[] args) {
        int x=1;
        int sum=1;
        System.out.println("请输入数字n:");
        Scanner in=new Scanner(System.in);
        int i=in.nextInt();
        String s = " ! =";
        while(x<=i){
            sum=sum*x;
            if (x<i){
                s = s + '*' + x;
            }
            else{
                s = s +"*" + x + "=" + sum;
            }
            x++;
        }
        System.out.println(i+s);
    }
}

 

 

 

相关标签: Java n的阶乘