c++ - 如何在 C++ 中打印二维数组?

标签 c++ arrays multidimensional-array 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];
    }
}
}

最佳答案

你的数组是

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];
    }
}

关于c++ - 如何在 C++ 中打印二维数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34730878/

相关文章:

c++ - 存储在异常对象 : providing strings in exception 中的信息

C++ 将 char 变量转换为字符串变量返回 ASCII 值

C++0x 和 lambda

python - 找到最大的差异 - O(n)

c++ - 在 C 和 C++ 中创建点数组

javascript - 使用 Google Apps 脚本从数组中获取最后一个值

php - 如何从多维数组输出值

c++ - 为什么我可以在没有着色器的情况下渲染一个正方形?

java - java中使用Arraylist的动态二维数组

c# - 锯齿状数组上的 array.Contains()