程序正在从文件中读取最大的数字,但不是最小的数字

Program is reading the largest number from a file, but not the smallest

本文关键字:数字 文件 读取 程序      更新时间:2023-10-16

我正在编写一个程序,该程序从输入文件中读取整数,并使用while循环找到最小和最大的数字并将其输出。我的输出文件成功地显示它找到了最大的数字,但它说最小的数字是 0,即使在我的输入文件中最小的数字是 11。这是我的代码:

#include <fstream>
#include <string>
#include <iomanip>
#include <iostream>
using namespace std;
int main()
{
fstream instream;
instream.open("lab7_input.txt");
ofstream outstream;
outstream.open("lab7_output.txt");
int next, largest, smallest;
largest = 0;
smallest = 0;
while (instream >> next)
{
if (largest < next)
{
largest = next;
}
if (smallest > next)
{
smallest = next;
}
}
outstream << "The largest number is: " << largest << endl;
outstream << "The smallest number is: " << smallest << endl;
instream.close();
outstream.close();
return 0;
}

这是您的问题:smallest = 0;

测试最小值/最大值时,请尝试将minmax变量初始化到光谱的另一端。使用INT_MININT_MAX来执行此操作。试试这个:

#include <climits>
...
int next, largest, smallest;
largest = INT_MIN;
smallest = INT_MAX;

现在,无论您的数字集中是什么,都可以确保程序具有最大/最小值。

我建议将最大值和最小值设置为第一个值:

instream >> largest;
smallest = largest;
while (instream >> next)
//...

这允许您的答案指定给定数字集中的最大和最小。 设置为数字限制,不会在集合中指定数字。

if(最小>下一个(,但如果最小为 0,则永远不会大于下一个 所以它总是粘在零, 使程序运行集最小 = 99999999//开头的高数字