首页 文章

在MATLAB中嵌套用于循环流控制

提问于
浏览
0

尝试使用matlab中的复合兴趣公式编写函数来计算不同的帐户余额 . 在这种情况下,它需要能够支持多个利率和年数输入 . 我目前正在使用嵌套for循环,它适用于第一组利率,但它只运行计算第二个和利息输入数组中任何更晚值的最后几年

function ans =  growth_of_money(P,I,n)

    disp(['     P     ','n     ','I    ','Total']);

 for I = I
      for n = n

          disp([P,n,I,compound_interest(P,I,n)]);

      end 

  end

end

function T = compound_interest(P,I,n)

T= P.*((1.+I).^n);

end

这是我目前得到的输出:

P     n     I    Total
 2     1     4    10

 2     3     4   250

       2           3           7        1024

我错过了什么?我怎样才能让它回到第二次运行的第一个n值?

1 回答

  • 0

    正如其他人所指出的那样,你的代码存在很多问题 . 您可以检查下面的代码,找出如何改进代码 . 对于单值输入(例如,n的一个值,I中的一个) .

    function growth_of_money(P,I,n)
        T = compound_interest(P,I,n);
        fprintf(1,'P: %.1f;   N: %.1f;   I: %.1f;   Total: %.1f; \n',P,I,n,T);          
    end
    
    function T = compound_interest(P,I,n)    
        T= P.*((1.+I).^n);    
    end
    

    对于多值输入,并假设您要使用 disp 函数(实际上,这不是理想的),您可以使用以下内容:

    function growth_of_money(P,I,n)
    
            disp('P    N   I  Total');    
    for i=I
        for k=n
            T = compound_interest(P,i,k);
            disp([P i k T]);    
        end
    end
    
    end
    
    function T = compound_interest(P,I,n)    
        T= P.*((1.+I).^n);    
    end
    

相关问题