递归 练习

递归

  • 递归就是A方法调用A方法!自己调用自己。
  • 利用递归可以用简单的程序来解决一些复杂的问题。他通常只把一个大型复杂的问题层层转化为一个与原问题相似的规模较小的问题来求解,递归策略只需要少量的程序就可秒输出解题过程所需要的多次重复计量,大大地减少了程序的代码量。递归的能力在于用有限的语句来定义对象的无限集合。
  • 递归结构包括两部分:
    • 递归头:什么时候不调用自身方法。如果没有头,将陷入死循环。

    • 递归体:什么时候需要调用自身方法。

    package com.zhz.method;
    
    public class Demo07 {
        public static void main(String[] args) {
            Demo07 test = new Demo07();
            test.test();
        }
        public void test(){
            test();
    
        }
    
    }
package com.zhz.method;

public class Demo06 {
    //5! 5*4*3*2*1
    public static void main(String[] args) {
        System.out.println(z(5));
    }
    public static int z(int n){
        if (n == 0){
            return 1;
        }else{
            return n*z(n-1);
        }
    }
}

计算器

package com.zhz.method;
//计算器
public class CalculatorDemo {
    public static void main(String[] args) {
        CalculatorDemo test = new CalculatorDemo();
        int sum = test.sum(10,70);
        int difference = test.difference(90,33);
        double product =test.product(14,44);
        double quotient =test.quotient(777,111);
        System.out.println("加法运算结果为 "+ sum);
        System.out.println("减法运算结果为 "+ difference);
        System.out.println("乘法运算结果为 "+ product);
        System.out.println("除法运算结果为 "+ quotient);

        System.out.println("加法的结果为 "+ test.sum(707,44));

    }



    public int sum(int a,int b){
    int result1 = a + b;
    return result1;
    }
    public int difference(int a,int b){
        int result2 = a - b;
        return result2;
    }
    public double product(double a ,double b){
        double result3 = a * b;
        return result3;
    }
    public double quotient(double a,double b){
        double result4 = 0;
        if (b != 0){
            result4 = a / b;
        }else {
            result4 = 0;
        }
        return result4;
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值