필터 지우기
필터 지우기

How do I find the last number that added up to or over 10000?

조회 수: 1 (최근 30일)
Collin Kerr
Collin Kerr 2016년 3월 31일
댓글: Star Strider 2016년 3월 31일
x = 1;
while x<10000
x = x + 2;
end
disp(x)

답변 (1개)

Star Strider
Star Strider 2016년 3월 31일
Well, you’re summing ‘x’ so you’re also using it as a counter.
The obvious answer is ...
x
  댓글 수: 2
Collin Kerr
Collin Kerr 2016년 3월 31일
편집: Collin Kerr 2016년 3월 31일
Using this code it tells me x is 10001, what im trying to figure out is, how do I tell matlab to pinpoint what the last number was that added up to 10001. Or if I wanted to ask it what was the number that added up x to 501. It starts of 1 + 3 + 5 + 7, which adds up to 16 so 7 was the number that added to 16.
Star Strider
Star Strider 2016년 3월 31일
For that, you need to add a counter that increments after the addition:
x = 1;
k = 0;
while x<10000
x = x + 2;
k = k + 1;
end
Here, ‘k’ is the number of iterations.
To find the last value of ‘x’, you need to add a summing variable (here ‘s’) and test for it:
x = 1;
s = 0;
k = 0;
while s<10000
x = x + 2;
s = s + x;
k = k + 1;
end
So now, ‘s’ is the sum, ‘x’ is the last number added, and ‘k’ is the number if iterations.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by