log算法 matlab_[LOG]MATLAB递归累加器算法实现

0x00 Accumulator 1(推荐)

%
disp(Accumulator(100));
%
function [Results]=Accumulator(n)
    if n ~= 0
        Results=Accumulator(n-1)+n;
    else
        Results=0;
    end
end

0x01 Accumulator 2(不推荐)

%
function [Sum]=Accumulator(min,max,Sum)
    %
    if min<=max
        %
        Sum=Sum+min;
        %
        min=min+1;
        %
        Accumulator(min,max,Sum);
    else
        %
        global Value;
        %
        Value=Sum;
        %
        return;
    end
end

0x02 Main

%
Accumulator(1,100,0);
%
global Value;
%
disp(Value);

0x03 Run

>> test
        5050

0x04 Value

  • 在MATLAB中,当程序调用函数时,函数的【执行位置】只要首次脱离【该函数的领空】,此函数则立即返回不会等待递归完毕

065aa6ecdb4d589bddc8022396031afe.png
  • 因此想要返回递归完毕后的Sum,这里采用了Global的办法。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值