使用递归 (Ruby) 查找阶乘时,以下代码查找整数的阶乘,但在 float 的情况下失败。我该如何调整呢? 我考虑过像在数学中那样使用域,但我还不知道该怎么做。
def factorial num
if num < 0
return "Please provide a whole number."
end
if num <=1
1
else
num * factorial(num-1)
end
end
最佳答案
过滤 float 的最简单方法是使用使它们 float 的东西:) 它们不能被 1 整除。
def factorial num
if (num % 1 != 0 || num < 0)
return "Please provide a whole number."
end
if num <=1
1
else
num * factorial(num-1)
end
end
希望对您有所帮助。干杯
关于ruby - 如何从 Ruby 中的阶乘方法中排除 float ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40798368/