How does the following loop turn out to be different from the expected 25?

1 回表示 (過去 30 日間)
Qiandong Dong
Qiandong Dong 2022 年 11 月 18 日
回答済み: Walter Roberson 2022 年 11 月 18 日
s=0;
I=5;
for i=1:I
for j=1:i
s=s+1
end
end
s = 1
s = 2
s = 3
s = 4
s = 5
s = 6
s = 7
s = 8
s = 9
s = 10
s = 11
s = 12
s = 13
s = 14
s = 15
value(s)
Unrecognized function or variable 'value'.

回答 (1 件)

Walter Roberson
Walter Roberson 2022 年 11 月 18 日
Your inner loop is j=1:i . The first time that is j=1:1 . The second time it is j=1:2 . The third time it is j=1:3, then 1:4, then 1:5 . So the inner loop is going to run 1+2+3+4+5 = 15 times.

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by