数组格式问题并将数组传递给函数

时间:2014-05-09 04:24:42

标签: c++ arrays

我的问题是这个程序的数组。

到目前为止,我有这个

#include <iostream>
#include <fstream>
using namespace std;

const int NUM_SCORES = 3;
const int NUM_STUDENTS = 5;

double getClassAverage(const double[], int);
double getStudentAverage(const double[], int);
double getHighest(const double[], int);

int main()
{
    const int ARRAY_SIZE = 15;
    int numbers[ARRAY_SIZE];
    int count = 0;
    ifstream inputFile;

    inputFile.open("p6.dat");

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

    inputFile.close();

    cout << "The numbers are: ";
    for (count = 0; count < ARRAY_SIZE; count++)
        cout << numbers[count] << " ";
    cout << endl;
    return 0;
}   

//Function for averaging columns for Test Average.
getClassAverage(const double , int size)
    for (int col = 0; col < NUM_SCORES; col++)
    {
         double total, average;
         total = 0;

         for (int row = 0; row < NUM_STUDENTS; row++)
             total += scores[row][col];

         average = total / NUM_STUDENTS;

         cout << "Score average for test "
              << (row + 1) << " is " << average << endl;
    }

//Function for averaging rows for Student Average.  
getStudentAverage(const double , int size)
    for (int row = 0; row < NUM_STUDENTS; row++)
    {
         double total, average;
         total = 0;

         for (int col = 0; col < NUM_SCORES; col++)
             total += scores[row][col];

         average = total / NUM_SCORES;

         cout << "Score average for student "
              << (row + 1) << " is " << average << endl;
    }

//Function for finding highest test score in array.
getHighest(const double , int size)
    for (int col = 0; col < NUM_SCORES; col++)
    {
          int count;
          int highest;
          highest = numbers[0];

          for (int row = 0; row < NUM_STUDENTS; row++)
          {
              if (numbers[coount] > highest)
                  highest = numbers[count];
          }

             cout << "The highest score is " << highest << endl;
    }

当我运行该程序时,它显示它就像我将它保存在文件中一样,但是我想将它从单行转换为二维矩阵(3 x 5)。

p6.dat的内容:

  

75 78 86 91 72 99 87 70 60 50 40 20 64 79 95

 75 78 86
 91 72 99
 87 70 60 
 50 40 20
 64 79 95

我是否可以摆脱const int ARRAY_SIZE并将其替换为分别为行和列设置为3和5的两个变量名称?我希望矩阵格式化的方式设置它,以便第一行是第一个学生3测试分数,重复学生#2,依此类推。列代表测试1-3。然后我有一些关于将数组传递给某些函数进行计算的问题。

1 个答案:

答案 0 :(得分:2)

我认为继续使用1-D阵列是最简单的(或者更好,使用vector,然后可以调整其大小)。

如果您想在3x5表格中输出15个项目,只需修改输出循环,每3个项目后打印一个换行符。

如果某个函数需要知道每一行的长度,那么只需将其作为另一个变量传递。