Heim  >  Fragen und Antworten  >  Hauptteil

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下结果是不同的,仍然求解

PHPzPHPz2712 Tage vor807

Antworte allen(2)Ich werde antworten

  • 阿神

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

    ruby是什么版本的? 我在2.0.0下运行结果正常

    Antwort
    0
  • PHP中文网

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

    1.9.2 下结果也正常

    P.S. 使用ruby请不使用return

    Antwort
    0
  • StornierenAntwort