使用递归函数和 do-while 循环时得到不正确的总和

Getting incorrect sum while using a recursive function and a do-while loop

我刚刚为一个学校项目完成了一个小函数的编码并得到了正确答案。然而,在添加了一个 do-while 循环之后(因为它是必需的),我开始 运行 进入问题。第一个循环工作得很好,我得到了正确的答案(即,如果我在函数中输入 20,它输出 210,这是正确的),但如果我输入相同的数字或不同的数字,数字将添加到前一个总数(所以如果我加 1,那么“总数”就是 211)。我希望每个循环都能找到总数,输出该总数,然后当出现新循环时,重新开始。我该如何解决这个问题?

#include <iostream>
using namespace std;

int n, total = 0; /* Global variables since I only have to declare it once rather than two times! */

int sum(int n);
// Recursive version to calculate the sum of
// 1 + 2 + .... + n


int main()
{
    char choice;
    do {
        cout << "Enter a positive integer:";
        cin >> n;
        sum(n);
        cout << "The sum of 1+...+" << n << " is: " << total << endl;
        cout << "Would you like to try another entry (Y/N): ";
        cin >> choice;
    }while(choice == 'Y' || choice == 'y');
    cout << "Goodbye!" << endl;
    return 0;
}


int sum(int n){
    if(n == 0) 
    {
      return total;
    }
    else
    {
      total = total + n;
      return sum(n-1);
    }
}

您可以为 sum 尝试以下代码:

int sum(int n) {
    if (n == 1) {
        return 1;
    } else {
        return n + sum(n - 1);
    }
}