我在獲取二維數組元素的最小值,最大值和平均值時遇到了問題。獲取二維數組中的平均值,最小值和最大值
我有一個包含學生和成績的二維數組。
我使用rand生成等級。例如當我輸入2,2打印出我
Courses : 01 02 Average Min Max
ID
01 8 50 29
02 74 59 29
,我的平均功能取第一個平均值,並且不會取其他平均值。
這是我的代碼;
int A[30][30];
int findAverage(int noOfStudents ,int noOfGrades){
float sum,average;
for (int i = 0 ; i < noOfGrades ; i++) {
for (int j = 0; j<noOfStudents; j++) {
sum += A[i][j];
}
average = sum/noOfGrades;
// cout << " " << format(average);
sum = 0;
return format(average);
}
在這裏我如何使用它
int main() {
int noOfCourses , noOfStudents;
cin >> noOfCourses >> noOfStudents;
cout << "Courses : " ;
for (int i = 0; i < noOfCourses; i++) {
if (i+1 >= 10) {
cout << i+1 << " ";
}else{
cout <<"0" << i+1 << " ";
}
}
cout << "Average Min Max";
for(int i=0; i<noOfStudents; i++) { //This loops on the rows.
for(int j=0; j<noOfCourses; j++) { //This loops on the columns
A[i][j] = genGrade();
}
}
cout << "\n ID " << endl;
for(int i=0; i<noOfStudents; i++) { //This loops on the rows.
if (i+1 >= 10) {
cout <<" " << i+1 << " ";
}else{
cout <<" 0" << i+1 << " ";
}
//cout <<" 0" << i+1 << " ";
for(int j=0; j<noOfCourses; j++) { //This loops on the columns
if (A[i][j] >= 10 && A[i][j] <=99) {
cout <<" " << A[i][j] << " ";
}
if(A[i][j] < 10) {
cout <<" " << A[i][j] << " ";
}
if (A[i][j] == 100) {
cout << A[i][j] << " ";
}
}
cout <<" "<<findAverage(noOfStudents,noOfCourses);
cout << endl;
}
}
我在做什麼錯?另外我怎麼能得到每陣列的最小值,最大值?
什麼是'A'的聲明? –
int A [30] [30]; ,對不起:) –
在使用它之前,你還沒有初始化'sum',並且在外循環的第一次迭代中返回。有沒有理由不使用'std :: vector'來存儲數據,'std :: accumulate'來加起來呢?您可以通過'min_element'和'max_element'獲得最小值和最大值。 –