Do not understand why my code isn't working!
1 visualizzazione (ultimi 30 giorni)
Mostra commenti meno recenti
The problem I am assigned says, ) Use a while loop to determine how many terms in the series 2k, k = 1, 2, 3, …, are required for the sum of the terms to exceed 1500. The program should print the count of the minimum number of terms needed to exceed 1500 using fprintf. Make sure the output tells the person looking at it what the number represents.
What I did was use a for loop to create a vector from 2^1 up to 2^11. (Because 2^11 > 1500) I then used a while loop to add each element in the vector up. This is my code. (This is not the completed assignment, I still need to do the displays and stuff, but I wanted to get the core structure done first.)
s=[1];
for i=1:11
s(i+1)=2^i;
end
summ=0;
k=1;
terms=0;
while k<=12
while summ<=1500
summ=summ+s(k);
terms=terms+1;
k=k+1;
end
end
When I run the program, it does nothing. I then press CTRL+C and see that "terms" and "sum" are correct. (I would have to subtract 1 from the terms because it is one term over 10.) Help!
0 Commenti
Risposte (1)
Andrew Newell
il 29 Mar 2011
The reason that is does nothing is that you are stuck in an infinite loop. The inner loop ( while summ<=1500 ) runs until k=12, then exits to the outer loop. Then you get this sequence happening over and over:
while k<=12 % true (k=12)
while summ<=1500 % false (skip to end)
...
end
end % k=12 because the inner loop was skipped
You don't really need the outer loop - you're aiming for a finite sum, so the inner loop will definitely terminate.
Another thing to think about: the terms in s are 1,2,4,8,16, ... Is that what the question asks for?
0 Commenti
Vedere anche
Categorie
Scopri di più su Loops and Conditional Statements in Help Center e File Exchange
Prodotti
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!