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
相关产品推荐
相关产品推荐

