【发布时间】:2015-08-06 06:50:47
【问题描述】:
我正在解决以下问题:
我意识到我的代码有点不对劲,但我想创建一个 for 循环来确定整数 x(输入值)是否至少小于或等于谐波级数之和。
这是我目前所拥有的:
function n =one_per_n(x)
if x > 10000
n = -1;
end
total = 0;
i = 0;
for i = 1:10000
if x >= total
n = ceil(total);
else
total = (1/i) + total;
end
end
我在 while 循环中添加了我的尝试。我意识到这是错误的,但任何帮助将不胜感激。
function n =one_per_n(x)
if x > 10000
n = -1;
end
total = 0;
i = 0;
for i = 1:10000
while total <= x
total = (1/i) + total;
end
end
n = 总数;
【问题讨论】:
-
找到
n后使用break退出循环(在if语句中) -
另外,不需要通过
i = i + 1;增加i。这已经由for循环本身完成 -
我理解这些概念,我只是有点难以将它们放在一起。当 for 循环的总和超过输入值时,我需要中断。
-
确实如此。在
n = ceil(total);之后休息。此外,第一次检查 (if x > 10000) 是无关紧要的。
标签: matlab function loops for-loop while-loop