how to use sum in while loop

I have another similar problem to the one i just asked. I still did not get the right answer. "Suppose you start adding the numbers 1 + 1/2 + 1/3 + 1/4 + 1/5+ ... together. Use a while loop to determine how many of these numbers you have to add in this way to get a sum that is greater than 4."
This is my code
a = 1;
c = 1;
t = a;
while t<4
c = c+1;
a = a+ 1/(a+1);
t = a+t;
end

回答 (1 件)

Star Strider
Star Strider 2020 年 9 月 12 日

1 投票

See if this does what you want:
c = 1;
t = 0;
while t<4
a = 1/c;
t = a+t;
c = c+1;
end
Check = find(cumsum(1./(1:50)) >= 4, 1, 'first');
The ‘Check’ test agrees.

2 件のコメント

Vy Do
Vy Do 2020 年 9 月 12 日
I got 32 using your code. However, the answer of this problem is 31. Do you know why?
Star Strider
Star Strider 2020 年 9 月 12 日
The code is correct. The counting problem depends on how the incrementation is done.
This produces the ‘correct’ result, the only difference being the initial value of ‘c’, and the location of the ‘c’ increment calculation in the code:
c = 0;
t = 0;
while t<4
c = c+1;
a = 1/c;
t = a+t;
end
Check = find(cumsum(1./(1:50)) > 4, 1, 'first');
.

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

カテゴリ

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

タグ

質問済み:

2020 年 9 月 12 日

コメント済み:

2020 年 9 月 12 日

Community Treasure Hunt

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

Start Hunting!

Translated by