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

C++实现输入整数到-1停止输出总和平均最值功能的故障排查

问题原因

  • 你将终止标记-1也存入了存储输入值的vector中,导致计算最小值、总和、平均值时都把无效的终止值纳入统计,是两个异常的核心诱因
  • 你在循环内部重复声明了avg2、sum1、tsum变量,和外层声明的变量属于不同作用域,逻辑容易混乱
  • 每次循环都重复计算总和、平均值属于无意义的性能消耗,且你在输入-1后直接使用了刚计算的包含-1的统计结果
  • 平均值计算时没有排除终止值对应的额外计数,即使你给总和加了1修正,分母还是多了1,所以平均值结果错误

修正后的代码

#include <iostream>
#include <vector>
#include <numeric>
#include <algorithm>
using namespace std;

int main()
{
    vector<int> v; // 输入均为整数,用int类型即可满足需求
    int n = 0;

    while (true) {
        cout << "Give me another number, or enter '-1' to stop:" << endl;
        cin >> n;
        // 先判断是否为终止标记,是就直接退出循环,不存入vector
        if (n == -1) {
            break;
        }
        v.push_back(n);
    }

    // 先判断是否存在有效输入,避免出现除以0的报错
    if (v.empty()) {
        cout << "未输入任何有效数值" << endl;
        cout << "All Done" << endl;
        return 0;
    }

    // 所有统计逻辑在输入完成后统一计算
    int sum = accumulate(v.begin(), v.end(), 0);
    float avg = (float)sum / v.size();
    int min_val = *min_element(v.begin(), v.end());
    int max_val = *max_element(v.begin(), v.end());

    // 输出结果
    cout << "Total sum: " << sum << endl;
    cout << "Average: " << avg << endl;
    cout << "\nMin Element: = " << min_val << endl;
    cout << "\nMax Element: = " << max_val << endl;
    cout << "All Done" << endl;

    return 0;
}

内容的提问来源于stack exchange,提问作者jcwilson11

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 17:06:02