簡體   English   中英

如何執行以下遞歸函數?

[英]How do I do the following recursive function?

好的,所以我有一個常規的Node列表,其中包含成員信息和下一個。

我需要遞歸地使用一個函數來計算平均值,然后比較每個節點是否大於平均值。

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));

並且節點中只有1個5,然后該函數返回1。所以一切都按預期進行,但我一直得到0。

以下是節點的主要功能和其他功能。

#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);


}

我不確定您的代碼是否定義了行為。 但是,這條線

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

取決於是先計算左加數還是右加數。

如果它是左數,則Acount遞歸遞減avg直到avg等於列表中的元素數(此處是main例程調用的從零開始的10個元素)。 請注意, avg是通過引用傳遞的。 因此,當遞歸返回時,該術語在正確的求和中

Node->info > avg

永遠不會為真,因為在fill例程中將Node->info設置為小於元素數量的值。

在C ++中,沒有表達式的從左到右(或從右到左)評估順序的概念。 操作符優先級將控制的關聯性,但在的情況下, f1() + f2()沒有保證f1()被調用之前f2() (反之亦然)。 它可能取決於編譯器或其他。

我的建議是將表達式分成兩個不同的語句,如下所示:

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

我認為您的方法無效。

在此語句中:

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

您不知道第二項的評估時間。 它沒有在C ++中定義。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM