我想使用c ++和多维数组计算每个学生的平均值。在下面的代码中,它将显示每个学科的每个学生的成绩。如何列出所有分数,最后显示每个学生的平均成绩?
这是我的代码:
#include <iostream>
using namespace std;
const int ROWS = 4;
const int COLS = 4;
void fillScores(int[ROWS][COLS]);
void printScores(int[ROWS][COLS]);
int main()
{
int scores[ROWS][COLS];
fillScores(scores);
printScores(scores);
return 0;
}
void fillScores(int newScores[ROWS][COLS]){
int score;
for(int i = 0; i < ROWS; i++){
cout << "Enter scores for exam " << (i + 1) << ": ";
for(int j = 0; j < COLS; j++){
cin >> score;
newScores[i][j] = score;
}
}
}
void printScores(int newScores[ROWS][COLS]){
for(int i = 0; i < COLS; i++){
cout << "Student " << (i + 1) << " Scores: ";
for(int j = 0; j < ROWS; j++){
cout << newScores[j][i] << " Average Score: " << (newScores[j][i]/COLS);
}
}
}
答案 0 :(得分:1)
如果您只想打印它(而不将其存储在变量中),则可以在打印时进行:
void printScores(int newScores[ROWS][COLS]){
for(int i = 0; i < COLS; i++){
cout << "Student " << (i + 1) << " Scores: ";
float examsum = 0;
for(int j = 0; j < ROWS; j++) {
examsum += newScores[j][i];
cout << newScores[j][i] << " ";
}
cout << "Average: " << examsum/ROWS << endl;
}
}