在我的数组循环中找不到正确的最大值

时间:2018-12-01 01:55:17

标签: c++ arrays for-loop

因此,我的教授给了我们这个项目,以读取文本文件并找到最大值,最小值和。但是由于某种原因,当我编写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 90656 117 595 415 948 126 4 558 571 87 42 360 412 721 463 47 119 441190985214509 2571 77 8168165165199593 74 310 9 995 561 92 14 288 466 664 892 8 766 34639 151 64 98 813 67 834 369

最大值是: 51 <---我不知道这个数字是从哪里来的...

2 个答案:

答案 0 :(得分:1)

51来自以下行:

maxVal=myArray[0];

在循环中尝试找到最大的元素:

for (j=0; j< 210; j++)
    if (myArray[j] > maxVal){
        myArray[i]=maxVal;
    }
}

但是,这会将maxVal分配给myArray[i],这不是您想要的。首先,您需要分配myArray[j],而不是myArray[i],其次,您需要将maxVal分配给较大的值。因为是maxVal=myArray[0];,所以是您唯一一次为maxVal分配任何内容,这就是为什么它是51(字符3的ASCII值,它是第一个字符你读)。您需要执行以下操作:

if (myArray[j] > maxVal){
     maxVal = myArray[j];
}

我相信您希望myArray成为int[]。还有一种更好的方法是不要有两个for循环并循环直到EOF,而在myFile >> myArray[i]时循环:

int myArray[210];
int i = 0;
//...
while (myFile >> myArray[i]) {          
    cout << myArray[i] << " ";  
    if (myArray[i] > maxVal) {
        maxVal = myArray[i];
    }
    i++;
}   

输入文件的哪个

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

返回:

995

答案 1 :(得分:-1)

要实现您想要的目标,就不能像这样进行比较

if (myArray[j] > maxVal){

因为myArray[j]是一个字符(肯定不包含您感兴趣的整数),而maxVal是一个int值。这也是您看到51的原因-尝试将整数存储到char中时,您实际上仅从流中读取8位(这导致0到254之间的某个值,基本上是从8位块开始的值)。您的输入流)。

您肯定想要类似的东西

char myArray[32][210]; 

能够将流中的完整整数读取到这210个char *插槽之一中。 然后,在比较(并分配给maxValue)时,您需要将文本int值转换为数字值,例如,使用atoi()。