我应该编写一个程序来读取并填充一个包含 5 个学生 ID 和他们的成绩的数组,然后使用学生的 ID 打印平均成绩、最低成绩和最高成绩,例如: 学生 1:111 56 学生 2:222 98 学生 3:333 90 学生 4:444 68 学生 5:555 88 平均:80 排名第一:222 98 排名#5:111 56 我的程序给了我乱七八糟的值(平均值为 328.4,排名#1:444 555,排名#5:555 88)以及调试错误(运行时检查失败#2 - 变量“a”周围的堆栈被破坏), 在这里
#include <iostream>
using namespace std;
void avg(double a[4][1]);
void minMax(double a[4][1]);
void main () {
double a[4][1];
cout << "Enter 5 students' IDs and marks:\n";
int studentNum = 1;
for (int r=0; r<5; r++) {
cout << "Student" << studentNum << ": ";
studentNum++;
for (int c=0; c<2; c++)
cin >> a[r][c]; }
avg(a);
minMax(a); }
void avg(double a[4][1]){
double sum=0.0;
for (int r=0; r<5; r++) {
for (int c=1; c<2; c++) // does not include the ID column
sum = sum + a[r][c]; }
double avg = sum/5; // number of students = 5
cout << "Average: " << avg << endl; }
void minMax (double a[4][1]) {
double min = a[0][1];
double max = a[0][1];
int minID = a[0][0];
int maxID = a[0][0];
for (int r=0; r<5; r++) {
for (int c=1; c<2; c++) {
if (a[r][c] < min){
min = a[r][c];
minID = a[r][0]; }
if (a[r][c] > max){
max = a[r][c];
maxID = a[r][0]; } } }
cout << "Rank#1: " << maxID << " " << max << endl;
cout << "Rank#5: " << minID << " " << min << endl; }
非常感谢任何帮助,非常感谢!
最佳答案
错误是:
double a[4][1];
应该是:
double a[5][2];
关于c++ - 计算二维数组的平均值、最小值、最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16261922/