如何在C++中用输入字符串"no"终止程序并完成向量统计
Fix: Terminate on "no" Input Instead of 0 for Your C++ Number Collection Program
Let's sort out this issue—your current code uses 0 as the termination trigger, but 0 is a valid number that gets included in your calculations, which isn't what you want. Here's how to adjust it to stop when the user types "no", plus clean up some messy logic along the way:
Key Issues in the Original Code
- You're reading directly into a
double, so you can't check for the string "no" first. - The nested
while(number==0)loop creates confusing, clunky logic, and 0 ends up in your vector when it shouldn't. - Using
accumulatewith anintinitial value (0) will cause precision loss when calculating the mean.
Modified Code
#include <iostream> #include <string> #include <vector> #include <algorithm> #include <numeric> #include <sstream> #include <limits> using namespace std; int main() { vector<double> numbers; string input; cout << "Hello! Enter as many numbers as you would like!\nWhen you are finished, enter \"no\"" << endl; while (true) { cout << "Enter a number or \"no\": "; cin >> input; // Check if user wants to terminate input if (input == "no") { break; } // Try converting the input string to a double stringstream ss(input); double number; if (ss >> number) { numbers.push_back(number); } else { cout << "Invalid input! Please enter a number or \"no\"." << endl; // Clear input error state and ignore leftover junk to avoid infinite loops cin.clear(); cin.ignore(numeric_limits<streamsize>::max(), '\n'); } } // Handle edge case where no numbers were entered if (numbers.empty()) { cout << "No numbers were entered. Nothing to calculate!" << endl; return 0; } // Calculate and display all statistics cout << "\nNumbers you entered: "; for (double num : numbers) { cout << num << " "; } cout << endl; cout << "Total size of the Numbers vector: " << numbers.size() << endl; double max_val = *max_element(numbers.begin(), numbers.end()); cout << "Max Value: " << max_val << endl; double min_val = *min_element(numbers.begin(), numbers.end()); cout << "Min Value: " << min_val << endl; double sum = accumulate(numbers.begin(), numbers.end(), 0.0); // Use 0.0 to preserve double precision double mean = sum / numbers.size(); cout << "Mean Value: " << mean << endl; return 0; }
What Changed & Why
- Input Handling Overhaul: We first read into a
stringto check for "no" before attempting any number conversion. This lets us terminate cleanly without adding invalid values to the vector. - Error Resilience: Added a
stringstreamto safely convert input to adouble. If the user types something that isn't a number or "no", we let them know and reset the input buffer to avoid stuck loops. - Cleaner Logic Flow: Moved all statistic calculations outside the input loop—we only run them once after the user decides to stop entering numbers.
- Precision Fix: Swapped the
accumulateinitial value from0(anint) to0.0(adouble), which prevents integer division from messing up decimal results. - Edge Case Coverage: Added a check for empty vectors so we don't try to calculate stats when no numbers were entered.
内容的提问来源于stack exchange,提问作者Morrese Morrison
相关产品推荐
相关产品推荐

