尝试编写一个函数来使用 Matlab 中的复利公式计算不同的账户余额。在这种情况下,它需要能够支持多个利率和年数输入。我目前正在使用 nested 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
我错过了什么?如何让它在第二次运行 I 时返回到 n 的第一个值?
正如其他人指出的那样,您的代码有很多问题。您可以检查下面的代码以了解如何改进代码。对于单值输入(例如,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