Home  >  Q&A  >  body text

Ruby求阶乘,第二个方法为什么不能自动转换成长整数?

def f(n)
  i = 1
  while n > 0
    i *= n
    n -= 1
  end
  return i
end

def f2(n)
  if n == 1
    return 1
  else
    return n * f2(n-1)
  end
end

puts f(22)
puts f2(22)

运行结果

:!ruby test.rb  | tee /var/folders/_y/prf_0rd90dj668w8cp6fr8gc0000gn/T/vYzoU63/38
1124000727777607680000
-1250660718674968576
(1 of 2): 1124000727777607680000

呃…发现在vim中使用外部命令和在shell下结果是不同的,仍然求解

PHPzPHPz2762 days ago855

reply all(2)I'll reply

  • 阿神

    阿神2017-04-21 11:19:56

    What version of ruby ​​is it? I ran it under 2.0.0 and the result was normal

    reply
    0
  • PHP中文网

    PHP中文网2017-04-21 11:19:56

    The results under 1.9.2 are also normal

    P.S. Please do not use return when using ruby

    reply
    0
  • Cancelreply