为何C++递归单词计数代码中两个cout输出结果不同?
递归统计单词数两次输出不一致的原因
先看你提供的代码:
#include <iostream> using std::cin; using std::cout; int count_end(char *a, int start, int ctr) { if (a[start] == '.') { cout << ctr << "\n"; return ctr; } else if (a[start] == ' ' && a[start - 1] != ' ') { ctr++; } start = count_end(a, start + 1, ctr); return ctr; } int main() { char sentence[1000]; cin.getline(sentence, 1000); int x; x = count_end(sentence, 1, 1); cout << "is count" << x << "\n"; return 0; }
核心错误分析
两次输出不一致的根源在于递归函数的返回值处理和参数传递逻辑错误:
错误的返回值传递
你把递归调用count_end的返回值赋值给了start变量,最后却返回当前函数栈中的ctr,而非递归得到的最终计数结果。当递归走到终止条件(遇到.)时,输出的ctr是经过所有递归层累加后的正确值,但上层函数没有把这个正确值传递回去,而是返回了自己栈内未同步更新的ctr副本。值传递导致的计数无法同步
ctr是按值传递给递归调用的,每一层递归中修改的ctr都是当前函数栈的局部副本,不会影响上层调用的ctr。只有将下层递归返回的正确计数结果逐层传递回上层,main函数才能拿到最终的正确值。
修正方案
修改递归函数的返回逻辑,直接返回递归调用的结果,去掉错误的start赋值:
int count_end(char *a, int start, int ctr) { if (a[start] == '.') { cout << ctr << "\n"; return ctr; } else if (a[start] == ' ' && a[start - 1] != ' ') { ctr++; } // 直接返回递归调用的结果,不再赋值给start return count_end(a, start + 1, ctr); }
修改后,每一层递归都会把下层得到的最终计数结果传递回上层,main函数中的x就会和终止时输出的ctr值完全一致。
内容的提问来源于stack exchange,提问作者Akshat Kushwah
相关产品推荐
相关产品推荐

