我有以下红宝石代码:
def xyz(n)
case n
when 0
0
when 1
1
else
xyz(n - 1) + xyz(n - 2)
end
end
puts xyz(ARGF.gets.to_i)
我将代码执行为:
Ruby$ echo "4" | ruby test.rb
我想知道答案是如何变成3
的。我不明白为什么:
xyz(n - 1) + xyz(n - 2)
代码的一部分。请解释一下。
发布于 2018-06-06 06:49:09
它是一个recursive
函数,由itself
调用一个函数
下面是与每个步骤不同的steps of the function execution
和output
:
步骤1:
def xyz(n)
n = 4.
case n
when 0
0
when 1
1
else
n = 4, so it comes here and calls
xyz(n - 1) + xyz(n - 2)
xyz(3) + xyz(2) // no result
end
end
No /p,因为这两种条件都可以进行递归调用
步骤2:
def xyz(n)
n = 3.
case n
when 0
0
when 1
1
else
n = 3, so it comes here and calls
xyz(n - 1) + xyz(n - 2)
xyz(2) + xyz(1) // recursion stops here as case 1 is 1 // so o/p is 1 for hjere
end
end
o/p为1,因为xyz(1)将执行到1。当前O/p: 1整体O/p: 1
步骤3:
def xyz(n)
n = 2.
case n
when 0
0
when 1
1
else
n = 2, so it comes here and calls
xyz(n - 1) + xyz(n - 2)
xyz(1) + xyz(0) // 1
end
end
这里的o/p又是1,因为xyz(1)
1
**,将执行当前的O/p: 1总体O/p: 1+1 ==> 2**
步骤4:
def xyz(n)
n = 2.
case n
when 0
0
when 1
1 // 1
else
n = 1, I wont come here
xyz(n - 1) + xyz(n - 2)
end
end
这里的o/p又是1,因为case 1
1
**,将执行当前的O/p: 1总体O/p: 1+1+1 ==> 3**
所以,最后的输出是3
https://stackoverflow.com/questions/50713133
复制相似问题