How to display the number of iterations a while loop does?
37 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Wing Lin
le 7 Oct 2017
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
le 7 Oct 2017
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).
Réponses (1)
Image Analyst
le 21 Fév 2013
Modifié(e) : Image Analyst
le 13 Avr 2019
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 commentaires
Walter Roberson
le 1 Jan 2021
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);
Voir également
Catégories
En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!