Calculate the number of years the money will last?

조회 수: 2 (최근 30일)
nada Elmoghany
nada Elmoghany 2015년 4월 8일
댓글: Jonathan Campelli 2015년 4월 9일
my program is supposed to calculate the # of years the money will last for each retiree.. each year 2.5% interest is added onto the balance and the individuals withdraws 4.5%. So i created a While loop but the loop just keeps repeating, it doesn't stop. I think my main problem is that i dont no what to write for the conditional statement of While loop. Here's what i have so far
No_of_elements = 7;% the number of retirees
min_years = 40;
max_years = 50;
*% # of years of employment
r = round(min_years + (max_years-min_years).*rand(No_of_elements,1))
% deposit '
x = (400000-300000 * r-min(r)) ./ max(r) - min(r) + 300000
W = 0; % the initial withdrawal amount
years = 0;
while x >= W
format bank
% the interest
i = x*0.025
% the balance after the interest is added
B= x+i
% the amount of withdrawal
W = B*0.045
% the balance after the withdrawal
x = B-W
years = years+1;
if x<=0
fprintf ('the number of years: %d \n',years)
end
end
  댓글 수: 3
nada Elmoghany
nada Elmoghany 2015년 4월 8일
편집: nada Elmoghany 2015년 4월 8일
oh sorry about that, that was a typo.. its supposed to W not Z, and the B1 is supposed to B. Sorry
dpb
dpb 2015년 4월 8일
Suggest you then edit your code to reflect the changes...

댓글을 달려면 로그인하십시오.

채택된 답변

Jonathan Campelli
Jonathan Campelli 2015년 4월 8일
Nada, your While loop was not breaking because your x values were never reaching zero. I've crafted a nested while loop that stops looping when your "bank account" dips below 1 Cent, or $0.01:
No_of_elements = 7;% the number of retirees
min_years = 40;
max_years = 50;
r = round(min_years + (max_years-min_years).*rand(No_of_elements,1)) % deposit '
x = (400000-300000 * r-min(r)) ./ max(r) - min(r) + 300000
W = 0.01; % the initial withdrawal amount
years = zeros(1,numel(x))';
for count=1:numel(x)
while x(count)>W
x(count)=x(count)+(x(count)*0.025)-(x(count)*0.045);
years(count)=years(count)+1;
end
end
years
  댓글 수: 2
nada Elmoghany
nada Elmoghany 2015년 4월 8일
Thank you very much for your help... That question was honestly frustrating me. Thanks again
Jonathan Campelli
Jonathan Campelli 2015년 4월 9일
You're welcome. I'm glad I could be of help.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Startup and Shutdown에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by