我的代码遇到的问题是 min 总是读取 0。原因是我没有正确地将它初始化为“random.txt”的第一个值。我该怎么做?
这是我的代码:
using namespace std;
int main()
{
ifstream inputFile;
//open file
inputFile.open("random.txt");
int numCount = 0;
int number, max, min, i, x;
double average, sum;
while(inputFile >> number)
{
for (i = 0; i < numCount; i++)
{
x = number;
if (x < min)
{
min = x;
}
else if (x > max)
{
max = x;
}
}
numCount++;
sum = number + sum;
}
if (numCount > 0)
{
average = sum/numCount;
}
inputFile.close();
cout << "Number of numbers is: " << numCount << endl;
cout << "Sum of numbers is: " << sum << endl;
cout << "Average of numbers is: " << average << endl;
cout << "Max of numbers is: " << max << endl;
cout << "Min of numbers is: " << min << endl;
return 0;
}