C++ do-while循环不按条件终止、负整数统计结果错误问题求助
C++代码问题排查结果
你的代码存在两处核心逻辑错误,对应你反馈的两个异常,具体问题和修复方案如下:
错误1:循环逻辑错误,无法在录入指定个数后停止
问题原因
你没有设置录入次数计数器,当前的循环终止条件while (userInput<numberInput)是将用户录入的数值和待录入个数做比较,二者完全无逻辑关联,自然无法按录入次数终止循环。
修复方案
新增计数变量int count = 0,每次完成一次数据录入后将计数+1,循环条件修改为count < numberInput。
错误2:负整数统计结果错误
问题原因
你的正负判断逻辑存在漏洞:if (userInput>0) {positives++;} else {negatives++;}将0也纳入了负整数的统计范围,0既不是正数也不是负数,该逻辑会导致负数统计结果偏大、正数统计结果正常、0统计值正确但被重复计入负数。
修复方案
调整正负判断逻辑,仅当userInput < 0时才累加负整数计数。
额外优化点
你的代码中存在手动调用main()的写法,这是C++标准明确禁止的未定义行为,建议替换为外层循环实现多轮录入的需求。
修正后完整代码
#include <iostream> using namespace std; int main() { char trial1; do { int numberInput; int userInput; int evens = 0; int odds = 0; int zeros = 0; int positives = 0; int negatives = 0; int count = 0; cout<<"How many numbers are you going to enter? "; cin>> numberInput; cout << endl; do { cout << "Enter data: "; cin >> userInput; cout << endl; // 正负统计逻辑修正 if (userInput>0) { positives++; } else if (userInput < 0) { negatives++; } else { zeros++; } // 奇偶统计逻辑优化 if (userInput != 0) { if (userInput % 2 == 0) { evens++; } else { odds++; } } count++; // 录入次数累加 } while (count < numberInput); // 循环条件修正 cout<<"Odd numbers entered: "<<odds<<endl; cout<<"Even numbers entered: "<<evens<<endl; cout<<"Positive integers: "<<positives<<endl; cout<<"Negative integers: "<<negatives<<endl; cout<<"Zero integers: "<<zeros<<endl; cout << "\nWould you like to input another set?"; cout << "\nIf YES press <y> and if NO press <n>: "; cin >> trial1; } while(trial1 == 'y'); // 替换原手动调用main的非法逻辑 cout << "\n-The program will now end-\n"; cout << "\n-Thank you for using the program-\n\n\n\n"; return 0; }
内容的提问来源于stack exchange,提问作者Edrick Paras
相关产品推荐
相关产品推荐

