【问题标题】:Smallest integer greater than or equal to harmonic series of input大于等于输入谐波级数的最小整数
【发布时间】: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 &gt; 10000) 是无关紧要的。

标签: matlab function loops for-loop while-loop


【解决方案1】:

你不需要使用一些循环:

function n = one_per_n(x)
lim   = min(10000,exp(x));
value = cumsum(1./(1:lim));
n     = find(value >= x,1); 
if isempty(n)
    n = -1;
end

【讨论】:

  • 很好,但实际上考虑到您的内存,该解决方案并不是那么有效。 lim 必须在 x 上,a 的长度会更大。你可以使用value = cumsum(1 ./ (1 : lim));
【解决方案2】:

我认为在这种情况下,while 循环是更好的选择

function [total, n] = one_per_n(x)
% This is a good initial check, good work
if x > 10000
    n = -1;
    return;
end

% Initialize the variables
total = 0;
n = 0;

% While not finished
while (total < x)
    % Number of terms
    n = n + 1;
    total = total + 1/n;
end

end

【讨论】:

  • 谢谢,我将用while循环发布我更新的代码。这是错误的,但如果有人能指出我的错误,我将不胜感激。
  • 你应该在if之后使用return
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-24
相关资源
最近更新 更多