Counting how many times a loop loops.
63 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Giuseppe
am 26 Mär. 2014
Kommentiert: Giuseppe
am 26 Mär. 2014
This is my code I want the user to enter a number they beleive the loop will run for until the running sum of integers is 21.
% Input Varibles
g = input('guess how many times');
% Constant Varibles
n = randi ([1, 11]);
max_21 = 21;
% Calculate Running Sum.
for a=n
sum = sum + a;
if sum>21
disp (sum)
else sum = sum + a;
end
end
What I want it to do is loop throgh the random integers and create a running sum. When the sum exceeds 21 I want it to stop. I need to calculate how many times it loops. Then I want to compare the ammount of loops to the inputed guess. Thinking about it now I may need a while loop. Could someone help me out im stuck.
Thanks,
0 Kommentare
Akzeptierte Antwort
Chandrasekhar
am 26 Mär. 2014
Bearbeitet: Chandrasekhar
am 26 Mär. 2014
Check the code below.
% Input Varibles
g = input('guess how many times');
% Calculate Running Sum.
loopcnt = 0;
sum = 0;
while(sum <=21)
n = randi ([1, 11]);
sum = sum + n;
loopcnt = loopcnt + 1;
end
disp (sum);
disp(['number of loops: ' num2str(loopcnt)]);
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!