C++ 带有.txt文件的数组出现问题 //声明变量 常量int数组_SIZE=12;//数组大小 整数[数组大小];//12元素数组 int最高,最低,总计=0,计数=0; 双倍平均; IFFS; /*****加工科*****/ fs.open(“numbers.txt”); 如果(fs.is_open()) { cout数字[计数]) {count++; 最高=数字[数组大小]; 用于(计数=1;计数最高) 最高=数字[计数]; } 最低=数字[数组大小]; 用于(计数=1;计数

C++ 带有.txt文件的数组出现问题 //声明变量 常量int数组_SIZE=12;//数组大小 整数[数组大小];//12元素数组 int最高,最低,总计=0,计数=0; 双倍平均; IFFS; /*****加工科*****/ fs.open(“numbers.txt”); 如果(fs.is_open()) { cout数字[计数]) {count++; 最高=数字[数组大小]; 用于(计数=1;计数最高) 最高=数字[计数]; } 最低=数字[数组大小]; 用于(计数=1;计数,c++,arrays,C++,Arrays,此代码使用带有以下数字的number.txt文件: 47 89 65 36 12 25 17 8. 62 10 87 62 我的程序不断向我输出错误的结果,如: 已成功打开numbers.txt 最大值为0 最低值为3 这些数字之和是0 这些数字的平均值为2.09204e-317,立即出现一个错误:您正在访问一个超出范围的数组元素: // Declareing variables const int ARRAY_SIZE = 12; // Array size int n

此代码使用带有以下数字的number.txt文件: 47 89 65 36 12 25 17 8. 62 10 87 62

我的程序不断向我输出错误的结果,如:

已成功打开numbers.txt

最大值为0

最低值为3

这些数字之和是0


这些数字的平均值为2.09204e-317,立即出现一个错误:您正在访问一个超出范围的数组元素:

    // Declareing variables
    const int ARRAY_SIZE = 12; // Array size
    int numbers[ARRAY_SIZE];    // Array with 12 elements
    int highest, lowest, total = 0, count = 0;
    double average;
    ifstream fs;

    /***** Processing Section *****/
    fs.open ("numbers.txt");
    if (fs.is_open())
    {
       cout << "Successfully opened numbers.txt\n";
       fs.close();
    }
   else
    {
       cout << "Error opening file";
    }

    while (count < ARRAY_SIZE && fs >> numbers[count]) 
    {count++;

        highest = numbers[ARRAY_SIZE];

        for (count = 1; count < ARRAY_SIZE; count++)
        {
          if (numbers[count] > highest)
             highest = numbers [count];
        }

        lowest = numbers[ARRAY_SIZE];

        for (count = 1; count < ARRAY_SIZE; count++)
        {
          if (numbers[count] < lowest)
             lowest = numbers [count];
        }

        for (int count = 0; count < ARRAY_SIZE; count++)
             total += numbers[ARRAY_SIZE];

        for (int count=0; count < ARRAY_SIZE; count++)
             total += numbers[ARRAY_SIZE];
             average = total / ARRAY_SIZE;
    }
数组的索引从0开始,因此最高的索引是
ARRAY\u SIZE-1

最简单的解决方案是:

    highest = numbers[ARRAY_SIZE];
第二个错误是,您没有首先将所有数字读入数组。由于此程序希望您使用数组,因此很可能您应该读取数组中的所有数字,一旦读入,您将循环计算最高和最低数字

highest = numbers[0];
//...
lowest = numbers[0];
while(计数>数字[count])
计数++;
//在此之后,循环计算最高值和最低值
第三个错误是,您在确认文件存在后关闭了该文件。您应该保持该文件处于打开状态

while (count < ARRAY_SIZE && fs >> numbers[count]) 
   count++;
// after this, loop for computing the highest and lowest 
if(fs.is_open())
{
库特
if (fs.is_open())
{
   cout << "Successfully opened numbers.txt\n";
   // do not call fs.close()!!
}