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 件のコメント

Andreas Goser
Andreas Goser 2011 年 3 月 8 日
I posted a suggestion to your first question. Can you test this and then re-consider / edit this one?

回答 (2 件)

Walter Roberson
Walter Roberson 2011 年 3 月 8 日

0 投票

Please see this FAQ
Matt Fig
Matt Fig 2011 年 3 月 8 日

0 投票

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