c++ - 计算二维数组的平均值、最小值、最大值

标签 c++ arrays function 2d

我应该编写一个程序来读取并填充一个包含 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/

相关文章:

c++ - visual studio 2012 因断点而崩溃

c++ - Visual Studio _CrtDumpMemoryLeaks 总是跳过对象转储

静态库中与 std::string 相关的 C++ undefined symbol

arrays - 在没有相交线的情况下连接MATLAB中的随机点

javascript - 使用 vanilla JS 删除 ES5 及以下版本数组中的重复数字的最快方法是什么?

JavaScript 切换函数

c# - 包装 C++ 函数以在 C# 中使用

Java - 将数组的数组拆分为多个数组

ios - 如何创建一个通用函数来加载 View Controller ?

function - 使用 Swift 结构构造函数作为函数