简体   繁体   English

有没有办法只将二维数组的一行作为参数?

[英]Is there a way to put as a parameter only one row of a 2d array?

I'm trying to call the getAverage function in the last cout on printResults, but when I call it, it just give me the same average for all the cases.我试图在 printResults 的最后一个 cout 中调用 getAverage function,但是当我调用它时,它只为所有情况提供相同的平均值。 For example, if I put that first students grades are 50 50 and 50, the average would come 50 for the second and third even if they have different scores.例如,如果我把第一名学生的成绩设为 50 50 和 50,那么即使他们的分数不同,第二名和第三名的平均分也会是 50 分。 I tried a loop with the first and second index, but it sums all of the points of each row.我尝试使用第一个和第二个索引进行循环,但它对每一行的所有点求和。 I want it to sum only the points of one row and give me the average.我希望它只对一行的点求和并给我平均值。 Then when I call it again sum the second row and give me the average.然后当我再次调用它时,对第二行求和并给我平均值。 All of this without declaring another variable.所有这一切都无需声明另一个变量。 (The code is an assigment and I have to do it this way) (代码是一个分配,我必须这样做)

#include <iostream>
using namespace std;

const int EXAMS = 3;
void getScores(int[][EXAMS], const int);

int getAverage(int[], const int); // this method requires an array and its length as parameters
char getGrade(int);
void printResults(int[][EXAMS], const int); 

int main() {
    const int STUDENTS = 5;
    int scores[STUDENTS][EXAMS] = {0};
    printResults(scores, STUDENTS);
    cout << endl;
    system("pause"); // for Visual Studio only
    return 0;
}

void getScores(int scores[][EXAMS], const int students)
{

    for (int i = 0; i < students; i++)
    {
        for (int j = 0; j < EXAMS; j++)
        {
            cout << "Enter the score for student #" << i + 1 << ", test #" << j + 1 << ": ";
            cin >> scores[i][j];
        }
        cout << endl;
    }
    
}

// The getAverage method receives an array and its length as parameters, and 
// returns an integer value. It computes the average by adding the values in 
// the array, which are stored in the integer variable sum, and then dividing 
// by the array's size. Use a for iteration control structure to add all the values.
int getAverage(int scores[][EXAMS], const int students)
{
    int sum = 0;
    for (int i = 0; i < EXAMS; i++)
    {
        sum += scores[0][i];
    }

    return sum / EXAMS;
}

// DO NOT DECLARE any variables in this method.
char getGrade(int finalAverage)
{
    if (finalAverage < 59)
        return 'F';
    else if (finalAverage < 69)
        return 'D';
    else if (finalAverage < 79)
        return 'C';
    else if (finalAverage < 89)
        return 'B';
    else
        return 'A';
}

// DO NOT DECLARE any variables in this method.
void printResults(int scores[][EXAMS], const int students)
{
    getScores(scores, students);

    for(int j = 0; j < students; j++)
    {
        cout << "The student with test scores ";
        for (int i = 0; i < EXAMS; i++)
        {
            if (i == EXAMS - 1)
                cout << "and " << scores[j][i] << ", ";
            else
                cout << scores[j][i] << ", ";
        }
        cout << "scored a final average of " << getAverage(scores, students) << " and earned a(n) " << getGrade(getAverage(scores, students)) << endl;
    }
}

I would solve it this way, without the function. But the assignment reequires me to do it with the function and without declaring any variables in the printResults method.我会这样解决它,没有 function。但是作业要求我使用 function 来完成它并且没有在 printResults 方法中声明任何变量。

void printResults(int scores[][EXAMS], const int students)
{
    getScores(scores, students);
    

    for(int j = 0; j < students; j++)
    {   
        int sum = 0;
        cout << "The student with test scores ";
        for (int i = 0; i < EXAMS; i++)
        {
            if (i == EXAMS - 1)
                cout << "and " << scores[j][i] << ", ";
            else
                cout << scores[j][i] << ", ";

            sum += scores[j][i];
        }
        cout << "scored a final average of " << sum / EXAMS << " and earned a(n) " << getGrade(sum / EXAMS) << endl;
    }
}

I solved it by putting the j counter as an input on the second parameter of the getAverage function.我通过将 j 计数器作为 getAverage function 的第二个参数的输入来解决它。

int getAverage(int scores[][EXAMS], const int student)
    {
        int sum = 0;
    
        for (int i = 0; i < EXAMS; i++)
            sum += scores[student][i];
        
        return sum / EXAMS;
    }
    
    
    
    
    void printResults(int scores[][EXAMS], int students)
    {
        getScores(scores, students);
    
        for(int j = 0; j < students; j++)
        {   
            int sum = 0;
            cout << "The student with test scores ";
            for (int i = 0; i < EXAMS; i++)
            {
                if (i == EXAMS - 1)
                    cout << "and " << scores[j][i] << ", ";
                else
                    cout << scores[j][i] << ", ";
            }
            cout << "scored a final average of " << getAverage(scores, j) << " and earned a(n) " << getGrade(getAverage(scores, j)) << endl;
        }
}

In the comments section of your question, you stated that the line在您问题的评论部分,您声明该行

int getAverage(int scores[][EXAMS], const int students)

was written by you and not provided by the assignment.是你写的,不是由作业提供的。

However, according to the code comments above the function definition (which I assume were provided by the assignment and not written by you), the function should only deal with a 1D array, ie a sub-array of the 2D array.但是,根据上面 function 定义的代码注释(我假设它是由作业提供的,而不是由您编写的),function 应该只处理一维数组,即二维数组的子数组。 Therefore, you should change the function signature to the following:因此,您应该将 function 签名更改为以下内容:

int getAverage( int scores[], int students )

Due to array to pointer decay (arrays themselves are not passed to functions, only pointers to arrays), this is equivalent to the following:由于数组到指针衰减(数组本身不传递给函数,只传递指向数组的指针),这等同于以下内容:

int getAverage( int *scores, int students )

Since the size of the array is passed to the function, the function should take this size into account.由于数组的大小传递给 function,因此 function 应该考虑这个大小。 Therefore, the function should be rewritten like this:因此,function应该这样改写:

int getAverage( int scores[], int students )
{
    int sum = 0;

    for ( int i = 0; i < students; i++ )
    {
        sum += scores[i];
    }

    return sum / students;
}

Now that the function getAverage only accepts a 1D array instead of a 2D array, the function call of getAverage in the function printResults should be rewritten to only pass a sub-array of the 2D array, instead of the entire 2D array:现在 function getAverage只接受一维数组而不是二维数组,function printResults 中getAverageprintResults调用应该重写为只传递二维数组的子数组,而不是整个二维数组:

void printResults(int scores[][EXAMS], const int students)
{
    getScores(scores, students);

    for(int j = 0; j < students; j++)
    {
        cout << "The student with test scores ";
        for (int i = 0; i < EXAMS; i++)
        {
            if (i == EXAMS - 1)
                cout << "and " << scores[j][i] << ", ";
            else
                cout << scores[j][i] << ", ";
        }
        cout << "scored a final average of " << getAverage(scores[j], EXAMS) << " and earned a " << getGrade(getAverage(scores[j], EXAMS)) << endl;
    }
}

Note that it is not very efficient to call getAverage twice with the same arguments, because this means that the average must be computed twice.请注意,使用相同的getAverage效率不是很高,因为这意味着必须计算两次平均值。 It would be better if you only called the function getAverage once and saved the result in a variable.如果您只调用一次 function getAverage并将结果保存在变量中会更好。 However, as far as I can tell, your assignment restrictions forbid declaring another variable, so you cannot follow this recommendation in this case.但是,据我所知,您的赋值限制禁止声明另一个变量,因此在这种情况下您不能遵循此建议。

It is also worth noting that it is common practice to use i as the loop counter of the outer loop and j as the loop counter of the inner loop.同样值得注意的是,通常的做法是使用i作为外循环的循环计数器,使用j作为内循环的循环计数器。 You are doing the opposite in your case, which is confusing for most programmers reading your code.你在你的情况下做相反的事情,这让大多数阅读你的代码的程序员感到困惑。

Additionally, even if this code works, it would probably be more logical to call the function getScores in the function main , instead of the function printResults .此外,即使此代码有效,在 function main中调用 function getScores而不是 function printResults可能更符合逻辑。 This is because the function name printResults implies that the function will only print the results, but not actually calculate the results.这是因为function这个名字printResults暗示function只会打印结果,而不会真正计算结果。

Therefore, if the restrictions on your assignment allow it, I would recommend removing the function call to getScores from the function printResults , and rewrite the function main like this:因此,如果您的作业限制允许,我建议从 function printResults中删除 function 对getScores的调用,并像这样重写 function main

int main() {
    const int STUDENTS = 5;
    int scores[STUDENTS][EXAMS] = {0};

    getScores(scores, STUDENTS);
    printResults(scores, STUDENTS);

    cout << endl;
    system("pause"); // for Visual Studio only

    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM