如何为一个方法绘制分解和组合图?

huangapple go评论65阅读模式
英文:

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.

here is the screenshot

答案1

得分: 1

a. 绘制fun(2,4)的分解与组合

您的问题听起来像是一个家庭作业任务,我不想替您完成这项工作。

不过,我可以为另一个示例绘制分解/组合图,以便让您有个想法。

下面是一个fun(0,3)的图示:

如何为一个方法绘制分解和组合图?

其中黑色箭头表示分解蓝色箭头表示组合,其中的fun(0,3)

分解过程(黑色):

  1. 绘制fun(0, 3)

  2. 通过检查您的代码,您可以看出,为了计算fun(0, 3),您首先必须计算fun(0, 2),所以您绘制了fun(0, 2)

  3. 为了计算fun(0, 2),您首先必须计算fun(0, 1),所以您绘制了fun(0, 1)

组合过程(蓝色):

  1. fun(0, 1) 返回 a,或在您的情况下是 0

  2. 您现在可以计算 fun(0, 2) = a + fun(0, 1) = 0 + 0 = 0

  3. 最后,您可以计算 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):

  1. Draw fun(0, 3)

  2. By examining your code, you can see that in order to compute fun(0, 3), you first have to compute fun(0, 2), so you draw fun(0, 2)

  3. In order to compute fun(0, 2), you first have to compute fun(0, 1), so you draw fun(0, 1)

The composition procedure (blue):

  1. fun(0, 1) returns a, or in your case 0

  2. You can now compute fun(0, 2) = a + fun(0, 1) = 0 + 0 = 0

  3. 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.

huangapple
  • 本文由 发表于 2020年10月18日 07:17:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/64408255.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定