You need to enable JavaScript to run this app. C++统计文件数据最值时最小值恒为0该如何解决?
优惠活动
大模型
产品
解决方案
定价
更多

C++统计文件数据最值时最小值恒为0该如何解决?

问题根源

所有最小值变量初始值被设为0,若你的data.txt文件中所有数值都大于0,c < smallest_1这类比较逻辑永远不会触发,最小值变量就会始终保留初始的0值。而最大值变量初始为0,只要数据中有大于0的数值就能正常更新,所以最大值统计结果符合预期。

修复方案

引入<climits>头文件,使用其中定义的int类型边界值初始化统计变量:

  • 所有最大值统计变量初始化为INT_MIN(int类型可表示的最小值)
  • 所有最小值统计变量初始化为INT_MAX(int类型可表示的最大值)

修复后代码

#include <iostream>
#include <fstream>
#include <string>
#include <climits> // 新增头文件
using namespace std;

int main()
{
    string input;
    ifstream nameFile("data.txt");

    if (!nameFile)
        return (cout << " ERROR : cannot open file.\n"), 1;

    while (getline(nameFile, input))
            cout << input << endl;

    nameFile.clear();
    nameFile.seekg(0);

    // 修改变量初始值
    int largest_1 = INT_MIN , smallest_1 = INT_MAX;
    int largest_2 = INT_MIN , smallest_2 = INT_MAX;
    int largest_3 = INT_MIN , smallest_3 = INT_MAX;

    for (int a {}, b {}, c {}, d {}, e {}; nameFile >> a >> b >> c >> d >> e; )
    {
        if (c > largest_1)
            largest_1 = c;

        if (d > largest_2)
            largest_2 = d;

        if (e > largest_3)
            largest_3 = e;

        if (c < smallest_1)
            smallest_1 = c;

        if (d < smallest_2)
            smallest_2 = d;

        if (e < smallest_3)
            smallest_3 = e;
    }


    std::cout << "The largest value 1 is " << largest_1 << '\n';
    std::cout << "The largest value 2 is " << largest_2 << '\n';
    std::cout << "The largest value 3 is " << largest_3 << '\n';

    std::cout << "The smallest value 1 is " << smallest_1 << '\n';
    std::cout << "The smallest value 2 is " << smallest_2 << '\n';
    std::cout << "The smallest value 3 is " << smallest_3 << '\n';
    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 07:57:01