#include<iostream>
#include<fstream>
using namespace std;
int main()
{
ifstream inFile;
ofstream outFile;
double sum;
double average;
int apple[50];
int b1;
int i;
outFile.open("apple_trip.txt");
for (i = 0; i < 50; i++)
{
b1 = rand() % 100;
outFile << b1 << endl;
}
outFile.close();
inFile.open("apple_trip.txt");
inFile >> apple[i];
for (apple[i] = 0; apple[i] < 100; apple[i]++)
{
if (apple[i] < 25)
{
cout << apple[i] << " people picked less than 25 apples";
if (apple[i] < 80 && apple[i] < 100)
{
cout << apple[i] << "number of apples is between 80 and 100";
}
}
}
return 0;
}
好吧基本上我必须输出50个随机数到一个outfile然后我必须关闭outfile并再次打开它。然后我必须使用for循环读取文件中apple的值,并在for循环中打印出以下语句。但是,我一直收到标题中所述的错误。我试过在互联网上看,但不能得出结论。我仍然是c ++的初学者。谢谢你的帮助。
答案 0 :(得分:2)
当您使用
从inFile
阅读时
inFile >> apple[i];
您始终将值保存到apple[i]
,而不会更改i
。因为你刚刚完成for循环,i
是50.我不知道你的数组的大小,但如果它正好是50,我怀疑,那么你写的是非法索引(50值表示有效索引从0到49)。
要解决这个问题,你必须在任何情况下都有另一个循环,你可以从中读取值,甚至当你循环通过它们来测试值是否低于20(或介于80和100之间)时,你的循环变量看起来是错误的。因此,您可以像这样更改代码:
outFile.open("apple_trip.txt");
for (i = 0; i < 50; i++)
{
b1 = rand() % 100;
outFile << b1 << endl;
}
outFile.close();
inFile.open("apple_trip.txt");
for (i = 0; i < 50; i++) // This loop ensures you don't keep overwriting
// the same value, which would be off by 1
{
inFile >> apple[i];
}
for (i = 0; i < 50; i++) // The loop variable is i, not apple[i], and we
// stop at 50
{
if (apple[i] < 25)
{
cout << apple[i] << " people picked less than 25 apples";
}
else if (apple[i] > 80 && apple[i] < 100) // change the first < to >
{
cout << apple[i] << "number of apples is between 80 and 100";
}
}
编辑:你的第二个if
检查该值是否介于80和100之间,是错误的:它被放在if (apple[i] < 25)
内。显然,它不会发生,所以我在那里更改了代码。