Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/295.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 区间上的斐波那契数(红宝石)_Ruby - Fatal编程技术网

Ruby 区间上的斐波那契数(红宝石)

Ruby 区间上的斐波那契数(红宝石),ruby,Ruby,有人能给我一个简单的解释为什么n+(n-1)不起作用吗?从数学上讲确实如此,但我不知道如何告诉ruby这就是我要找的?正如标题所示,代码应该返回斐波那契序列 startyear = [] (1..100).each do |n| puts n+(n-1) startyear.push(n) end n+(n-1)=2n-1。您的代码只是显示2n-1(1,3,5,7,…,199) 另一方面,startyear.push(n)将数字(1,2,3,100)推入startyear数组。我想你是

有人能给我一个简单的解释为什么n+(n-1)不起作用吗?从数学上讲确实如此,但我不知道如何告诉ruby这就是我要找的?正如标题所示,代码应该返回斐波那契序列

startyear = []
(1..100).each do |n|
  puts n+(n-1)
  startyear.push(n)
end
n+(n-1)=2n-1
。您的代码只是显示
2n-1
(1,3,5,7,…,199)

另一方面,
startyear.push(n)
将数字(1,2,3,100)推入
startyear
数组。我想你是想做这样的事

startyear = [1,1]
(2..100).each do |n|
  puts (new_num = startyear[n-1] + startyear[n-2])
  startyear.push(new_num)
end
但是,我不能100%确定这个范围在您的代码中代表什么,所以我可能错了。

n+(n-1)=2n-1
。您的代码只是显示
2n-1
(1,3,5,7,…,199)

另一方面,
startyear.push(n)
将数字(1,2,3,100)推入
startyear
数组。我想你是想做这样的事

startyear = [1,1]
(2..100).each do |n|
  puts (new_num = startyear[n-1] + startyear[n-2])
  startyear.push(new_num)
end

但是,我不能100%确定范围在代码中代表什么,所以我可能错了。

可能重复的范围意味着在值达到=>100时中断代码。我想这回答了我的问题,我在代码中添加了一个中断。非常感谢。当值达到=>100时,该范围将中断到代码。我想这回答了我的问题,我在代码中添加了一个中断。非常感谢。