How to display the number of iterations a while loop does?
41 ビュー (過去 30 日間)
古いコメントを表示
I'm trying to display the number of iterations a while loop goes through but I can't seem to figure it out. here's my code so far:
P = 250000;
A = 25000;
I = 4.5/100;
while P > A;
P = P*(1+I)-A;
P = P + 1;
end
I'm getting the correct amount of iterations but its outputting it as the 14 actual values rather than "14"
thanks
2 件のコメント
Wing Lin
2017 年 10 月 7 日
You can create a separate variable to store the number of iterations that your loop has run. For example,
count = 0; % kind of important to start at 0 for an accurate count
loopStart = 1; % arbitrary
loopEnd = 10; % arbitrary
while loopStart < loopEnd
count = count + 1; % this increments by 1 each time the loop executes
loopStart = loopStart + 5; % 5 is just some arbitrary constant that I chose to increment by
end
count % this should display 2 for this specific example
Image Analyst
2017 年 10 月 7 日
Since this is your answer, Wing, you should put it down in the Answers section, so you can get credit for it, rather than as a comment up here (which is usually just used to ask the poster for clarification of the question).
回答 (1 件)
Image Analyst
2013 年 2 月 21 日
編集済み: Image Analyst
2019 年 4 月 13 日
Try adding a loop counter:
P = 250000;
A = 25000;
I = 4.5/100;
counter = 1;
while P > A
P = P*(1+I)-A;
P = P + 1;
fprintf('Just finished iteration #%d\n', counter);
counter = counter + 1;
end
4 件のコメント
Walter Roberson
2021 年 1 月 1 日
P = 250000;
A = 25000;
I = 4.5/100;
counter = 1;
while P > A && counter < 10
P = P*(1+I)-A;
P = P + 1;
counter = counter + 1;
end
fprintf('finished %d iterations\n', counter);
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!