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

如何在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 accumulate with an int initial 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 string to check for "no" before attempting any number conversion. This lets us terminate cleanly without adding invalid values to the vector.
  • Error Resilience: Added a stringstream to safely convert input to a double. 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 accumulate initial value from 0 (an int) to 0.0 (a double), 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 07:12:38