c++ - 如何执行以下递归函数?

标签 c++ recursion nodes

好的,所以我有一个常规节点列表,其中包含成员信息和下一个。

我需要使用一个函数,递归地计算平均值,然后比较每个节点是否大于平均值。

int Acount(NodeType* Node, int sum, int& avg){

    if (Node == NULL){//last call
        avg = sum / avg;
        return 0;
    }
    else {
        return (Acount(Node->next, sum + Node->info, ++avg) + (Node->info > avg ? 1 : 0));
        }
}

这很简单。问题是返回的值始终为 0。 问题似乎出在

(Node->info > avg ? 1 : 0));

我已经完成了测试,当我执行以下操作时:

return (Acount(Node->next, sum + Node->info, ++avg) + Node->info;

return (Acount(Node->next, sum + Node->info, ++avg) + avg;

结果符合预期。在第一种情况下,我得到了 Node->info 的总和,而在第二种情况下,我得到了平均*节点数。

至此,我已经证明该功能运行良好。

但是说到

(Node->info > avg ? 1 : 0));

似乎有问题,这很奇怪。例如,如果我放置:

(Node->info == 5 ? 1 : 0));

节点中只有一个 5,然后函数返回 1。所以一切都按预期工作,但我一直得到 0。

以下是Node的主要功能和附加功能。

#include <iostream>
using std::cout;
using std::cin;
using std::endl;
struct NodeType{
    int info;
    NodeType *next;
};
//pre: first node passed is not NULL
int Acount(NodeType* Node, int sum, int& avg){

    if (Node == NULL){//last call
        avg = sum / avg;
        return 0;
    }
    else {
        return (Acount(Node->next, sum + Node->info, ++avg) + (Node->info > avg ? 1 : 0));
        }
}
void fill(NodeType*& Node){

    NodeType *temp;
    Node = new NodeType;
    Node->info = 0;
    Node->next = NULL;
    temp = Node;

    for (int i = 1; i < 10; i++){
        temp->next = new NodeType;
        temp = temp->next;
        temp->info = i;
        temp->next = NULL;
    }
}
void print(NodeType* Node){
    NodeType *temp = Node;
    while (temp != NULL){
        cout << temp->info << " ";
        temp = temp->next;
    }
    cout << endl;
}
void Delete(NodeType* Node){
    NodeType *temp;
    while (Node != NULL){
        temp = Node;
        Node = Node->next;
        delete temp;
    }
}
void main(){

    int sum = 0, avg = 0;
    NodeType *Node;
    fill(Node);
    print(Node);

    cout << Acount(Node, sum, avg) << endl;

    Delete(Node);


}

最佳答案

在 C++ 中,没有表达式从左到右(或从右到左)求值顺序的概念。运算符优先级将控制关联性,但在 f1() + f2() 的情况下,无法保证 f1()f2()< 之前被调用(反之亦然)。它可能取决于编译器或其他。

我的建议是将表达式拆分为 2 个不同的语句,如下所示:

int tmp = Acount(Node->next, sum + Node->info, ++avg);
return tmp + (Node->info > avg ? 1 : 0);

关于c++ - 如何执行以下递归函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33845378/

相关文章:

C 尝试添加撇号

graph - 如何在 gnuplot 上绘制树/图/网络数据?

c++ - 函数中的引用不会更改它之外的项目。 C++

c++ - Boyer Moore算法的正确实现

c++ - C++ 构造函数\析构函数中的奇怪行为

java - 从 Java 方法的递归调用生成 OL LI 树结构

关于链接列表中节点的混淆

c++ - 在 C++ 类中前向声明 typedef

c++ - VS2015从windows程序中删除linux上的文件

c++递归调用不将项目推送到 vector