英文:
How to draw a decomposition and composition for a method?
问题
考虑以下代码片段:
public int fun(int a, int b) {
if (b == 1)
return a;
else
return a + fun(a, b - 1);
}
a. 绘制 fun(2,4) 的分解与组合过程。
b. fun(2,0) 的值是多少?讨论并展示证明你答案的截图。
[这是截图链接][1]
注意:由于您要求只返回翻译好的部分,因此我只提供了翻译后的文本,不包含任何额外的内容。
英文:
Consider the following code fragment
public int fun(int a, int b) {
if (b == 1)
return a;
else
return a + fun(a, b - 1);
}
a. Draw the decomposition & composition of fun(2,4)
b. What would be the value of fun(2,0)?Discuss and show a screenshot that proves your answer.
答案1
得分: 1
a. 绘制fun(2,4)的分解与组合
您的问题听起来像是一个家庭作业任务,我不想替您完成这项工作。
不过,我可以为另一个示例绘制分解/组合图,以便让您有个想法。
下面是一个fun(0,3)
的图示:
其中黑色箭头表示分解,蓝色箭头表示组合,其中的fun(0,3)
。
分解过程(黑色):
-
绘制
fun(0, 3)
-
通过检查您的代码,您可以看出,为了计算
fun(0, 3)
,您首先必须计算fun(0, 2)
,所以您绘制了fun(0, 2)
-
为了计算
fun(0, 2)
,您首先必须计算fun(0, 1)
,所以您绘制了fun(0, 1)
组合过程(蓝色):
-
fun(0, 1)
返回a
,或在您的情况下是0
-
您现在可以计算
fun(0, 2) = a + fun(0, 1) = 0 + 0 = 0
-
最后,您可以计算
fun(0, 3) = a + fun(0, 2) = 0 + 0 = 0
b. fun(2,0)的值将会是多少?讨论并展示能证明您答案的截屏。
正如您所看到的,这种特殊情况会导致StackOverflow
错误。如果您尝试为该情况绘制分解/组合图,您将得到一个单一的、无限的分支。
英文:
> a. Draw the decomposition & composition of fun(2,4)
Your question sounds like a homework task and I don't want to do the work for you.
That said, I can draw the decomposition/composition diagram for another example to give you an idea.
Here's a diagram for fun(0,3)
:
where black arrows indicate the decomposition and blue arrows the composition of fun(0,3)
.
The decomposition procedure (black):
-
Draw
fun(0, 3)
-
By examining your code, you can see that in order to compute
fun(0, 3)
, you first have to computefun(0, 2)
, so you drawfun(0, 2)
-
In order to compute
fun(0, 2)
, you first have to computefun(0, 1)
, so you drawfun(0, 1)
The composition procedure (blue):
-
fun(0, 1)
returnsa
, or in your case0
-
You can now compute
fun(0, 2) = a + fun(0, 1) = 0 + 0 = 0
-
And finally, you can compute
fun(0, 3) = a + fun(0, 2) = 0 + 0 = 0
> b. What would be the value of fun(2,0)?Discuss and show a screenshot
> that proves your answer.
As you've seen, that particular case produces a StackOverflow
error. If you tried drawing a decomposition/composition diagram for that case, you'd end up with a single, endless branch.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论