程序正在从文件中读取最大的数字,但不是最小的数字
Program is reading the largest number from a file, but not the smallest
我正在编写一个程序,该程序从输入文件中读取整数,并使用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;
测试最小值/最大值时,请尝试将min
或max
变量初始化到光谱的另一端。使用INT_MIN
和INT_MAX
来执行此操作。试试这个:
#include <climits>
...
int next, largest, smallest;
largest = INT_MIN;
smallest = INT_MAX;
现在,无论您的数字集中是什么,都可以确保程序具有最大/最小值。
我建议将最大值和最小值设置为第一个值:
instream >> largest;
smallest = largest;
while (instream >> next)
//...
这允许您的答案指定给定数字集中的最大和最小。 设置为数字限制,不会在集合中指定数字。
if(最小>下一个(,但如果最小为 0,则永远不会大于下一个 所以它总是粘在零, 使程序运行集最小 = 99999999//开头的高数字
相关文章:
- 如何在C++中确定文本文件中的元素是字符还是数字
- 使用fstream对txt文件中的数字进行循环
- 如何在 C++ 中将文件中的逗号分隔数字读取到数组中?
- 为什么当我输入较大的数字时,我的程序会到达文件末尾?
- 如何从也包含C++字母的文本文件中提取某些数字?
- 如何将 UTF-8 文本从文件转换为某个可以迭代的容器,并检查每个符号是否为C++字母数字?
- 从.txt文件中读取浮点型数字并在公式中使用它们
- 在 txt 文件中显示前两个数字的程序
- 尝试将数字写入二进制文件时引发异常
- 为什么我的程序在读取/写入文件时会删除最重要的数字?
- C++:从文件中读取字符串和整数,并获得最大数字
- 一个C++程序,用于在输入位数时输出具有特定位数的 .txt 文件中的所有数字
- 如何读取具有数字间隔的文本文件?C++
- 如何知道文本文件中的输入是否是 C++ 中的有效数字
- 如何删除文件中的数字,通过 c++ fstream 的
- 在c++中读取文件时,它如何自动将字符放入字符数组,将数字放入整数变量
- 如何从txt文件c++中提取括号之间的数字
- 在获取从文件到矢量的每一行之后,数字将被更改或销毁
- 如何将数字输出到文件中,所有数字都具有相同的精度
- 将数字文件读入数组,同时每1026个条目跳过前两个值