如何用C ++打印2D数组?

时间:2016-01-11 20:54:41

标签: c++ arrays multidimensional-array 2d

我不确定如何打印这个2D数组。我在Visual Studio 2013中遇到了一致的错误。每次我尝试运行它时,它都会中断,有时会停止响应。如果您发现任何其他错误,请告诉我。谢谢你的帮助。

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

const int NUM_STUDENTS = 12;    // Number of students
const int NUM_QTRS = 4;         // Number of quarters

bool fillArr(double gpa[][NUM_QTRS]);
void averaging(double gpa[][NUM_QTRS], double avg[][12]);
void print(double avg[][12]);

int main()
{
double gpa[NUM_STUDENTS][NUM_QTRS]; // Array for 12 students, each with 4 quarters      
// define a 2D array called avg, which is 2 rows x 12 columns 
double avg[2][12];

// read from file and fill array with students gpas
if (!fillArr(gpa))
    return 1;

// Calculate average gpa for each student and store the student ID and average gpa of each student
averaging(gpa, avg);

// print the student ID and average gpa
print(avg);

// search for a student by ID
//search(avg);

// sort students by GPA
//sort(avg);
//print(avg);

return 0;
}

///// fill in the function definition below each description

// fillArr: read in from the file gpa.txt to fill the gpa array
bool fillArr(double gpa[][NUM_QTRS])
{
// open file
ifstream inFile;
inFile.open("gpa.txt");
if (!inFile)
{
    cout << "Error opening gpa.txt/n";
    return false;
}

// read data into gpa array
for (int row = 0; row < NUM_STUDENTS; row++)
{
    for (int col = 0; col < NUM_QTRS; col++)
    {
        inFile >> gpa[row][col];
    }
}
inFile.close();
return true;
}

// averaging: calculate and store the ID and average gpa of each student in avg array
void averaging(double gpa[][NUM_QTRS], double avg[][12])
{
double total = 0;
for (int row = 0; row < NUM_STUDENTS; row++)
{
    total = 0;
    for (int i = 0; i < NUM_QTRS; i++)
    {
        total += gpa[row][i];
    }
    avg[row][12] = total / NUM_QTRS;
}
}

// print: print the student ID and average gpa of each student
void print(double avg[][12])
{
cout << fixed << setprecision(2);
cout << "Student ID" << "\tAverage GPA" << endl;
for (int i = 0; i < 2; i++)
{
    for (int j = 0; j < 12; j++)
    {
        cout << avg[i][j];
    }
}
}

1 个答案:

答案 0 :(得分:1)

您的数组是

double avg[2][12];

for (int i = 0; i < 12; i++)
{
    for (int j = 0; j < 2; j++)
    {
        cout << i + 1 << avg[i][j] << "\t" << i + 1 << avg[i][j];
    }
    cout << endl;
}

这个for循环用于一个看起来像这个

的数组
double avg[12][2];

反转for循环。

for(int i = 0; i < 2; i++)
{
    for(int j = 0; j < 12; j++)
    {
        // print array
        cout << avg[i][j];
    }
}