You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++递归函数配合do-while循环计算累加和结果出错怎么解决?

问题根因

你代码的问题出在全局变量total的设计上:全局变量只会在程序启动时初始化一次为0,后续每次调用sum()函数都会直接修改这个全局变量的值,不会自动重置,所以多次计算时结果会叠加前一次的总和。

修复方案

这里提供两种可行的修复方式:

方案1:极简修复(保留现有逻辑,每次循环重置全局变量)

只需要在do-while循环内部,调用sum()函数之前把total赋值为0即可:

#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 {
        total = 0; // 新增:每次计算前重置累加值
        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);
    }
}

方案2:规范写法(移除全局变量,递归直接返回计算结果)

全局变量容易引发这类意料之外的状态残留问题,更推荐直接让递归函数返回累加结果,不需要依赖外部变量:

#include <iostream>
using namespace std;

// 递归函数直接返回1到n的和,不需要全局变量
int sum(int n);

int main()
{
    char choice;
    int n; // 将n改为局部变量
    do {
        cout << "Enter a positive integer:";
        cin >> n;
        int total = 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 0; // 递归终止条件直接返回0
    }
    return n + sum(n-1); // 每次递归累加当前n和后续的和
}
额外说明

方案2的写法更符合递归函数的设计规范,不存在全局变量的状态污染问题,即使多次调用也不会出现结果叠加的问题,更推荐使用。

内容的提问来源于stack exchange,提问作者user15649729

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 21:54:05