Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // 2019/12/28(土)
- // 階乗 再帰
- import java.util.Scanner;
- public class FactRec {
- public static void main(String[] args) {
- int lastNum;
- Scanner scanner = new Scanner(System.in);
- while (true) {
- System.out.println("階乗を求めます 0から20までの間の整数を入力して下さい");
- lastNum = scanner.nextInt();
- if (lastNum < 0 || lastNum > 20) {
- System.out.println("0から20までの間の整数を入力");
- } else {
- break;
- }
- }
- long result = factrial(lastNum);
- System.out.println(lastNum + "の階乗は" + result);
- }
- public static long factrial(long lastNum) {
- if (lastNum == 0) {
- return 1;
- } else if (lastNum >=1 && lastNum <= 20) {
- return lastNum * factrial(lastNum - 1);
- } else /* 誤入力用 */ {
- return 0;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement