【发布时间】:2018-12-01 01:55:16
【问题描述】:
所以我的教授给了我们这个项目来读取一个文本文件并找到最大值、最小值和总和。但是由于某种原因,当我编写 for 循环以查找最大值时,它返回的数字甚至不在文本文件中……而且我不知道我做错了什么。我将附上我的代码以及输出。谢谢
int main () {
ifstream myFile;
char myArray[210];
int i;
int maxVal;
int j;
int minValue;
double myAverage;
myFile.open("Lab #5A Data File.Txt", ios::in | ios::out);
if (myFile.is_open()) {
cout << "The file is open." << endl;
myFile >> noskipws;
while (!myFile.eof()){
for (i=0; i<210; ++i) {
myFile >> myArray[i];
cout << myArray[i];
}
myFile >>myArray[i];
}
maxVal=myArray[0];
for (j=0; j< 210; j++)
if (myArray[j] > maxVal){
maxVal=myArray[j];
}
当我运行代码时我得到了什么:
文件已打开。
346 130 982 90 656 117 595 415 948 126 4 558 571 87 42 360 412 721 463 47 119 441 190 985 214 509 2 571 77 81 681 651 995 93 74 310 9 995 561 92 14 288 466 664 892 8 766 34 639 151 64 98 813 67 834 369
最大值是:51
【问题讨论】:
-
当您尝试将最大值分配给 max 变量时:
myArray[i]=maxVal;。它应该是maxVal = myArray[j];(因为myArray[j]是您要与maxVal进行比较,而不是myArray[i]) -
为什么你把数字读成
chars,而不是ints?为什么myFile >> noskipws;?51是字符'3'的 ASCII 码,它是从文件中读取的第一个值。