How do I find the last number that added up to or over 10000?
2 次查看(过去 30 天)
显示 更早的评论
x = 1;
while x<10000
x = x + 2;
end
disp(x)
0 个评论
回答(1 个)
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 个评论
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 Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!