简体   繁体   English

请向我解释为什么这个函数不是递归的

[英]Please explain to me why this function is not recursive

My instructor insists that I am not writing recursive functions but has not provided any explanation of why my functions are not recursive.我的导师坚持我不是在写递归函数,但没有解释为什么我的函数不是递归的。 I've been researching recursive functions for weeks now but apparently still do not understand what makes a recursive function.我已经研究递归函数数周了,但显然仍然不明白什么是递归函数。 As far as I am able to gather, a recursive function is any function which calls itself using a matching function call to the original.据我所知,递归函数是任何使用对原始函数的匹配函数调用来调用自身的函数。

Psuedo example:伪示例:

bool foo(int someInt){
++someInt;
return foo(someInt);
}

Below is my latest function.下面是我最新的功能。

int LinkedList::sumR(int intIn){
    if(intIn == 0){
    if(head != NULL)
    curr = head;
    }  

    if (head != NULL){
        if(curr->next != NULL){
            intIn = intIn + curr->data;
            curr = curr->next;
            return sumR(intIn);
        }  
        else
        {              
            intIn = intIn + curr->data;
        }

    return intIn;
    }
return intIn;
}

I'm completely lost at this point.在这一点上,我完全迷失了。

Update更新

After emailing my instructor, they responded that for a function to be recursive it must accept a class or struct pointer as a parameter (as far as they're concerned, I guess).在给我的导师发电子邮件后,他们回答说,一个函数要递归,它必须接受一个类或结构指针作为参数(就他们而言,我猜)。

Without a mathematical definition it is hard to tell, but I think what your instructor expects is that you implement this as a pure function, not relying on any state external to the function (such as your variable named cur ).没有数学定义很难说,但我认为您的讲师期望您将其实现为纯函数,而不依赖于函数外部的任何状态(例如名为cur的变量)。

eg take the factorial function (5! = 5 x 4 x 3 x 2 x 1)例如采用阶乘函数(5!= 5 x 4 x 3 x 2 x 1)

int fact(n) = { 1 if n == 1 else n * fact(n-1) }

If I implement this the way you implemented your list sum above如果我按照您在上面实施清单总和的方式实施此操作

prod = 1
fact(n) {
    if (n > 1) {
       prod *= n;
       fact(n - 1);
    }
}

This second implementation relies on side-effects (the global state variable prod ).第二个实现依赖于副作用(全局状态变量prod )。

If your LinkedList is list of nodes LinkedList::Node (what your variable cur and head point to), then try to redefine your function as:如果您的LinkedList是节点列表LinkedList::Node (您的变量curhead指向的内容),则尝试将您的函数重新定义为:

int LinkedList::sumR(LinkedList::node cur);

and call it with sumR(list->head);并用sumR(list->head);调用它sumR(list->head);

Any recursive method will include the following three basic elements :任何递归方法都将包括以下三个基本元素

  1. A test to stop or continue the recursion.停止或继续递归的测试。
  2. An end case that terminates the recursion.终止递归的结束情况
  3. A recursive call(s) that continues the recursion.继续递归的递归调用。

Your first example is missing #2您的第一个示例丢失 #2

https://beginnersbook.com/2017/08/cpp-recursion/ https://beginnersbook.com/2017/08/cpp-recursion/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM