gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 05:33:33 25 4
gpt4 key购买 nike

我不确定如何打印这个二维数组。我在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com