手记

递归法求 5!

            首先这个题目要用到递归,递归就是自己调用自己的意思,直到条件不满足。            设计一个f方法            具体代码如下:                    public int f(int n){                        if(n>1){                            return n*f(n-1);}                            else{                                return 1;                            }                    }                    当传入参数为5时,                 5>1 返回5*f(4)                    f(4)则调用f方法传入参数为4   4>1 返回4*f(3)                                                        同理  3>1 返回3*f(2)                                                                    2>1 返回2*f(1)                                                                 1=1 返回1                    最后返回值为:5*4*3*2*1                     只要输出即可求出5!。

0人推荐
随时随地看视频
慕课网APP