Can you help me with the while loop?

2 ビュー (過去 30 日間)
Tri Dang
Tri Dang 2021 年 6 月 16 日
回答済み: Anagha Mittal 2021 年 6 月 17 日
I want in min years to make a final value to increase (but not exceeding 3 time the investment)
The code doesn't work
Can someone take a look?
numYears = 0;
while (FinalValue <= 3*Investment)
numYears=numYears+1;
FinalValue=Investment*power(1+Rate,numYears);
end
  1 件のコメント
Rik
Rik 2021 年 6 月 16 日
Apart from the missing initialization and the lack of formatting, there doesn't seem to be an issue.
What is the specific issue you're having?

サインインしてコメントする。

回答 (1 件)

Anagha Mittal
Anagha Mittal 2021 年 6 月 17 日
Missing initialization seems to be the issue. You need to initialize 'FinalValue' as 0 to remove the error as well as 'Rate' and 'Investment' to the suitable value.
Rate = 5; % use your desired value
Investment = 1000; % use your desired value
numYears = 0;
FinalValue = 0;
while (FinalValue <= 3*Investment)
numYears = numYears+1;
FinalValue = Investment*power(1+Rate, numYears);
end
% disp(FinalValue);
disp(numYears);
This code works but it displays the FinalValue to be greater than 3*Investment as anyhow the loop will run once, since initially the condition FinalValue <= 3*Investment is true. To achieve this condition, you may use an if statement within the loop to calculate previous year when your desired condition held.
Rate = 2; % use your desired value
Investment = 1000; % use your desired value
numYears = 0;
FinalValue = 0;
while (FinalValue <= 3*Investment)
numYears=numYears+1;
FinalValue=Investment*power(1+Rate,numYears);
if FinalValue > 3*Investment
numYears = numYears - 1;
break
end
end
% disp(FinalValue);
disp(numYears);

カテゴリ

Help Center および File ExchangeProgramming についてさらに検索

タグ

製品


リリース

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by