码迷,mamicode.com
首页 > 编程语言 > 详细

Java递归实现阶乘

时间:2019-11-04 15:24:02      阅读:94      评论:0      收藏:0      [点我收藏+]

标签:can   sys   pre   tin   else   exce   continue   正整数   nbsp   

import java.util.Scanner;

public class Factorial {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n;

        while (true) {
            System.out.print("请输入一个正整数(输入0退出循环):");
            try {
                n = sc.nextInt();
            } catch (Exception e) {
                System.out.println("错误的类型!");
                sc.nextLine();
                continue;
            }
            if (n == 0) {
                break;
            }
            System.out.printf("%d! = %d\n", n, fact(n));
        }

        System.out.println("再见!");
    }

    private static long fact(int n) {
        if (n < 0) {
            System.out.println("错误的数值范围!");
            return -1;
        } else {
            return factorial(n);
        }
    }

    private static long factorial(int n) {
        if (n == 1) {
            return 1;
        } else {
            return n * factorial(--n);
        }
    }
}

 

Java递归实现阶乘

Java递归实现阶乘

标签:can   sys   pre   tin   else   exce   continue   正整数   nbsp   

原文地址:https://www.cnblogs.com/noonjuan/p/11792039.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!