【Java菜鸟日记6】Java递归练习


前言

继续记录,跟着学了递归练习一个写了一个阶乘

开始

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package com.Mycode;

import java.util.Scanner;

public class RecursivePractice {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入一个整数:");
int NumberIn = sc.nextInt();
System.out.println(factorial(NumberIn));
sc.close();
}
public static double factorial(double n){
if(n == 0){
return 1;
}else
return n * factorial(n-1);
}
}

运行

没什么讲的,根据用户输入进行计算,当数量稍大时会显示Infinity
示例

1
2
999
Infinity

当数量过大时会显示

1
2
3
4
5
6
7
8
9
10
999999
Exception in thread "main" java.lang.StackOverflowError
at com.Mycode.RecursivePractice.factorial(RecursivePractice.java:17)
at com.Mycode.RecursivePractice.factorial(RecursivePractice.java:17)
at com.Mycode.RecursivePractice.factorial(RecursivePractice.java:17)
at com.Mycode.RecursivePractice.factorial(RecursivePractice.java:17)
at com.Mycode.RecursivePractice.factorial(RecursivePractice.java:17)
at com.Mycode.RecursivePractice.factorial(RecursivePractice.java:17)
at com.Mycode.RecursivePractice.factorial(RecursivePractice.java:17)
at com.Mycode.RecursivePractice.factorial(RecursivePractice.java:17)

收获

当数量过大时会导致栈溢出
非必学的技术,在java中应该尽量避免使用递归,只有处理量小的时候可以考虑使用


文章作者: 上江 Yayoi
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 上江 Yayoi !
  目录