What is the output after each recursive function call?
1 次查看(过去 30 天)
显示 更早的评论
Consider the following code:
function [out] = myRecurfn(num)
if floor(num) == 0
out = 2
else
out = 4 + myRecurfn(num-1)
end
end
When the above function is called with myRecurfn(3.5), what is the value of the output variable? Show your work, by showing what is ‘out’ for every call of the function and then how the final value is reached.
Since the value of out is only given for floor(num) == 0 (i.e. when num = 0.5) does that mean that the output for all the calls up to this point would just be: out = 4 + myRecurfn(3.5-1), out = myRecurfn(2.5-1), out = myRecurfn(1.5-1), and then the first output is out = 2? I am confused what is meant by a function call in this case, or what the output should look like for each call.
1 个评论
Jonas
2023-5-8
you are on the right way, but floor() does not mean -1 as you wrote. floor of 3.5 is 3, not 2.5.
floor calcultes the nearest smaller integer of the input if the input is not already integer
3.5 -> 3
2 -> 2
-1.5 -> -2
and so on
采纳的回答
Stephen23
2023-5-8
"I am confused what is meant by a function call in this case,"
A function call is every time a function is called. Usually functions are called by a user, e.g. when you write
sin(pi)
in the command line you are calling the SIN function. Inside a recursive function, a function calls itself (but the meaning has not changed at all). Every time this line is evaluated:
out = 4 + myRecurfn(num-1)
the function is called... and theoretically might have an output (to which 4 is added). Your assignment asks for the values of each of those outputs. Use DISP to display the function outputs.
myRecurfn(3.5);
These ouput values correspond to input values of 0.5, 1.5, 2.5, and 3.5 respectively. Why are they in that order?: consider when the output values are defined: on the very first call (from you the user) is the output value already calculated? No, an actual number can only exist after all the recursive calls are complete... ditto every other call exept the deepest one. The deepest function call finally outputs a value, to which you add four, which can then be returned to its calling function (which happens to be itself)... etc.
function [out] = myRecurfn(num)
if floor(num) == 0
out = 2;
else
out = 4 + myRecurfn(num-1);
end
disp(out) % display the function output
end
0 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!