如何才能收到此代码工作错误消息

问题描述 投票:-3回答:1

写一个采用整数n的方法;它应该返回n*(n-1)*(n-2)*...*2*1。假设n >= 0。作为特例,factorial(0) == 1。难度:容易。

def factorial(n)
  a = 1
  store = []
  result = n - a

  while a <= (n-1) 
    j = n * result
    store << j
    a += 1
    store.each |j|
      add each j in array
    end
  end

错误:

ruby 2.3.1p112(2016-04-26修订版54768)[x86_64-linux](repl):17:语法错误,意外的tIDENTIFIER,期待keyword_do或'{'或'('在数组中添加每个j ^(repl): 32:语法错误,意外的keyword_end,期望输入结束

ruby
1个回答
0
投票

此错误的原因

syntax error, unexpected tIDENTIFIER, expecting keyword_do or '{' or '(' add each j in array ^ (repl):32: syntax error, unexpected keyword_end, expecting end-of-input

是因为你在do之后缺少store.each

def factorial(n)
  a = 1
  store = []
  result = n - a

  while a <= (n-1) 
    j = n * result
    store << j
    a += 1
    store.each do |j|
      # Not sure what are you trying to do here
      add each j in array
    end
  end
end

你最后也错过了一个end

注意:此代码不会给出预期的输出。首先修复你的逻辑。

© www.soinside.com 2019 - 2024. All rights reserved.