【问题标题】:Calculating average, min, max of a 2d array计算二维数组的平均值、最小值、最大值
【发布时间】:2013-04-28 10:28:07
【问题描述】:

我应该编写一个程序来读取并填充一个包含 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,rank#1:444 555,rank#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; }

任何帮助将不胜感激,非常感谢!

【问题讨论】:

  • 删除你的代码会使下面的答案毫无用处,不要那样做。

标签: c++ arrays function 2d


【解决方案1】:

错误是:

 double a[4][1];

应该是:

double a[5][2];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多