Problems with while expression in a script

disp('This program will calculate the number of years required for a savings account earning 5% annual interest to reach target value.')
I = input('Please enter the intial ammount put in the account: ');
T = input('Please enter the target ammount for the account: ');
Y=0;
%Expression:
while T ~= I*(1.05^Y)
Y = Y+1;
end
fprintf('It will take %i years to save up for your target ammount.',Y)
The one thing I have a problem with is that it only works for very small numbers such as it taking one year to go from 1 to 1.05 or 2 years from 1 to 1.1025. Also, I want to make it have a message telling the user to re enter values if the target value is less than the initial value.

1 个评论

I posted a suggestion to your first question. Can you test this and then re-consider / edit this one?

回答(2 个)

As Walter intimates, this is a floating point issue. Instead of using a tolerance, you might want to think about the problem at hand. For example:
while T - I*(1.05^Y)>0
Y = Y+1;
end
Of course you should also put a check in your code which insures (or errors when appropriate) that T>I initially.

此问题已关闭。

产品

提问:

Leo
2011-3-8

关闭:

2021-8-20

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by