[英]How to print a 2D array in C++?
我不確定如何打印此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];
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.