フィルターのクリア

Help me with this question please....

1 回表示 (過去 30 日間)
Mohammed Safwat
Mohammed Safwat 2017 年 12 月 11 日
編集済み: Roger Stafford 2017 年 12 月 11 日
Write a loop to calculate the sum 1*2+2*3+3*4+ ... + 99*100. The answer is 333300
so far I have
total = 0;
for n = 1:100;
total = total + n;
end
fprintf('Total %d\n' , total)

回答 (2 件)

John D'Errico
John D'Errico 2017 年 12 月 11 日
編集済み: John D'Errico 2017 年 12 月 11 日
Your loop sums only the integers from 1 to n, not the product of consecutive integers. But, hey, you were close, and you made a credible effort.
total = 0;
for n = 1:99
total = total + n*(n+1);
end
fprintf('Total %d\n' , total)
There was actually a second problem with what you wrote. The desired sum will have only 99 terms to sum! So my loop goes only from 1 to 99.
  1 件のコメント
Mohammed Safwat
Mohammed Safwat 2017 年 12 月 11 日
Thanks John!

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


Roger Stafford
Roger Stafford 2017 年 12 月 11 日
編集済み: Roger Stafford 2017 年 12 月 11 日
An alternative formula which reduces the amount of computation would be:
n = 99;
total = n*(n+1)*(n+2)/3;
That is true for any positive integer n.

カテゴリ

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