For loop nested in while loop problem

I have written a while loop that is supposed to determine the value of the parameter "n" for "a" to exceed the value 300. I know "n" should be 17, but I'm getting a value of 4 instead. Does anyone see the problem?
The code is as follows:
a = 10;
k = 0.5;
n = 2;
while a < 300
for m = 1:5
a = a + (a*k) + n;
end
n = n + 1;
end

 採用された回答

Terry
Terry 2013 年 10 月 18 日

0 投票

I realized that I didn't reinitialize my "a" variable, thanks to Barmar's comment. Although the code might not look very efficient, this is what works for me:
a = 10;
k = 0.5;
n = 2;
while a < 300
a = 10;
for m = 1:5
a = a + (a*k) + n;
end
if a >= 300
break
end
n = n + 1;
end

その他の回答 (1 件)

Azzi Abdelmalek
Azzi Abdelmalek 2013 年 10 月 18 日
編集済み: Azzi Abdelmalek 2013 年 10 月 18 日

0 投票

Why are you using a for loop from 1 to 5? You are not supposed to increment n instead of m?

2 件のコメント

Terry
Terry 2013 年 10 月 18 日
I want to increment both "n" and "m." The "m" is supposed to iterate "a" 5 times for every new "n" value until "a" exceeds 300.
Anthony
Anthony 2013 年 10 月 18 日
matlab is telling you the correct answer. iterating the following for 5 times will give a pretty large number.
a = a + (a*k) + n;

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

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

質問済み:

2013 年 10 月 18 日

回答済み:

2013 年 10 月 18 日

Community Treasure Hunt

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

Start Hunting!

Translated by