递归可以命名为简单的函数调用吗? [英] Can Recursion be named as a simple function call?

查看:38
本文介绍了递归可以命名为简单的函数调用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑递归函数:

 1)   int calc(int num)
       {

 2)    sum=sum+num;//sum is a global variable

 3)    num--;

 4)    if(num==0)
 5)    return sum;

 6)    calc(num);

       }

它计算一个整数的总和.我的老师告诉我这不是递归,而是一个简单的函数调用,因为你需要通过num-- 作为参数并返回 calc(num--) .

It calculates the sum of an integer . My teacher told me it's not recursion, but a simple function call, because you need to pass num-- as an argument and return calc(num--) .

我很震惊,因为当函数调用自身时,我只知道一件事,它的递归.

I was shocked, as I knew only one thing when a function call itself, its recursion.

她也给出了理由,那行没有.23 额外存储在堆栈内存中.我不知道她指的是什么.所以在经历了堆栈存储之后:

She also gave the reason, that line no. 2 and 3 is stored extra in stack memory. I have no idea what she was referring to.So after going through stack storage thingy:

在这里,我注意到传递的函数参数是以递归方式传递的,就像我的 function 中的 n--.以便它们可以链接到下一个函数调用.

Here, I noticed that the function arguments passed are in a recursive way, like n-- in my function. So that they can be linked to the next function call.

为此,我们可以将其称为简单的函数调用而不是递归吗?

For just this sake, can we term it a simple function call instead of recursion?

推荐答案

即使您所呈现的内容从技术上讲是递归的,但老师的想法非常具体.另一种不依赖于全局的形式看起来像这样:

The teacher has something quite specific in mind even though what you presented is, technically, recursive. Another form which wouldn't depend upon the global would look something like this:

int calc(int num)  // Assume this is valid for non-negative numbers
                   // In that case, type "unsigned int" would be more appropriate
{
    if ( num < 0 )
        return -1;  // Consider this an error; won't happen in recursive case

    if ( num == 0 )
        return 0;

    return num + calc(num-1);
}

这篇关于递归可以命名为简单的函数调用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆