【问题标题】:I Need to Pass Array to a Function to Average Different Test Scores [duplicate]我需要将数组传递给函数以平均不同的测试分数 [重复]
【发布时间】:2018-10-08 04:23:21
【问题描述】:

这段代码的目标是通过一个函数传递一个数组(我已经很难理解了)。我用笔和纸检查了代码,但我想我只是知道的不够多,无法理解出了什么问题。我输入的所有考试成绩都只是推回了一个大得离谱的负数。我不是要求你们做我的作业,因为我真的很想尝试了解我在做什么,但是现在真的很感激任何帮助。

#include <iostream>

//function prototype
double average(int studentScores[], int size);
double studentScores[4];
bool runAgain(void);

int main() {
    do {
        int studentScores[4], size = 4, result;
        string score;

        cout << "This program will calculate the average of four diffrent exam scores." << endl;

        for (int i = 0; i < size; i++) {
            studentScores[i] = 0;
            cout << "Please Enter Exam Score " << i + 1 << ": ";
            getline(cin, score);
        }
        for (int i = 0; i < size; i++) {
            result = (studentScores[1] + studentScores[2] + studentScores[3] + studentScores[4]) / size;
            studentScores[i]++;
        }

        cout << "The Average Exam score is " << result << endl;
    } while (runAgain());

    system("pause");
    return 0;
}

//function implementation
double average(int studentScores[], int size) {
    for (int i = 0; i < size; i++) {

        return (studentScores[i]++ / size);
    }
}
bool runAgain(void) {
    char userResponse;

    cout << "\nWould you like to run again (y or n): ";
    cin >> userResponse;


    if (userResponse == 'y' || userResponse == 'Y')
        return(true);

    return(false);
}

【问题讨论】:

  • 我建议您阅读ericlippert.com/2014/03/05/how-to-debug-small-programs 以获取有关调试代码的提示。您可以添加cout 语句来打印变量的值,并查看它们是否与您通过笔和纸追踪确定的值相匹配。当您发现输出与您期望的不同的地方时,您应该edit您的问题来解释发生的位置。然后,我们可以通过解释导致问题和绊倒您的任何概念来提供帮助。
  • 欢迎来到 Jayus 网站!我会附和 Code-Apprentice 所说的;他们链接的页面包含许多提示,可以帮助您自己找出问题。即使您不这样做,这也是将来调试其他代码的好习惯,并且它可能还会帮助您将您在此处发布的示例程序缩减为显示相同错误的较小程序 - 而且,在反过来,会让你的问题变得更好,更有可能得到回答。
  • 除了我之前的评论之外,您还应该花点时间考虑一下如何计算四个数字的平均值。您能用语言描述您手动执行此操作的步骤吗?
  • 你的标题不好,因为它没有描述问题。不涉及任何函数(您的代码从不调用average())。
  • @melpomene 是的,这绝对是个问题。我能够编写一个程序,在没有函数的情况下平均分数,但作业需要一个,所以我尝试在其中扔一个,但我不知道如何与数组一起使用。

标签: c++ arrays function


【解决方案1】:

第一个明显的错误:

int studentScores[4]

studentScores 有 4 个元素,编号为 studentScores[0]studentScores[3]

但是你的代码在访问studentScores[4]

result = (... + studentScores[4]) / ...

它不存在(并且不访问studentScores[0],它存在)。

【讨论】:

  • 好吧,这是有道理的。所以我应该从 0 开始而不是从 1 开始计数?还有,当我计算结果时,它会在第二个 for 循环的内部还是外部?
  • @Jayus 这是你的代码。您应该能够解释它的每个部分的作用。就此而言,为什么还有第二个 for 循环?
  • 老实说,我认为唯一的原因是我教授的“示例代码”有第二个 for 循环。我不完全理解数组和循环,因为我们上周才介绍过它。我相信您需要多个循环才能编译代码。
【解决方案2】:

很高兴在不给你答案的情况下帮助你。

我将在你的代码中散布一些问题,当你得到意外输出时,你应该在以后的程序中问自己。

#include <iostream>

//function prototype
double average(int studentScores[], int size);
double studentScores[4];
bool runAgain(void);

int main() {
    do {
        int studentScores[4], size = 4, result;
        string score; 
        /* Above, you declared a string to store the user's input in.
           In C++, the string "4" DOES NOT equal the integer 4. 
           How will you handle the fact that the variable 'score' is of type
           string, but you want to work with integers?
           Is there an easy way to get rid of this issue? (hint: use cin)
        */

        cout << "This program will calculate the average of four diffrent exam scores." << endl;

        /* In the below for-loop, think about what the value of 'score' will be
           after each iteration. (Hint, getline replaces the existing value of score).
           Also, where is the code that saves the user's inputted numbers to an array?
           Learn how to write values to an array http://www.cplusplus.com/doc/tutorial/arrays/ 
        */

        for (int i = 0; i < size; i++) { 
            studentScores[i] = 0;
            cout << "Please Enter Exam Score " << i + 1 << ": ";
            getline(cin, score);
        }

        /* In the for-loop below, you already noticed that your array has random
           values in it. The comment about the above for-loop should address that issue.
           Equally important though is understanding what the heck is happening in this
           loop below. After you fix the bug in the for-loop above (which will
           get the values in the array to equal the user's inputs), you'll be faced 
           with issues in this loop below.
           My advice is to understand what happens when the program
           executes "studentScores[i]++". First, it gets the number in the array at 
           the ith+1 position, then it increments that number by 1. Cool, but what
           are you doing with the result of that? It's not being put to use anywhere.
           Also, note that because the array is never being updated, 
           the line above it just calculates the same number and stores it in 'result'
           every iteration of the loop.

        */
        for (int i = 0; i < size; i++) {
            result = (studentScores[1] + studentScores[2] + studentScores[3] + studentScores[4]) / size;
            studentScores[i]++;
        }

        cout << "The Average Exam score is " << result << endl;
    } while (runAgain());

    system("pause");
    return 0;
}

// this function doesn't seem to be used, but understanding what
// is wrong with it will help you understand how to code.
// First, note that once a function hits 'return', it will
// never execute any more code in that function.
// So here, your return statement in the for-loop will prevent an
// actual loop from occuring (since the function will exit as soon as the first loop iteration is entered)
// Second, note that you are just getting the value in the array and adding 1 to it
// before dividing it by 'size', which is not the formula for an average. 
double average(int studentScores[], int size) {
    for (int i = 0; i < size; i++) {

        return (studentScores[i]++ / size);
    }
}
bool runAgain(void) {
    char userResponse;

    cout << "\nWould you like to run again (y or n): ";
    cin >> userResponse;


    if (userResponse == 'y' || userResponse == 'Y')
        return(true);

    return(false);
}

我希望这些 cmets 有所帮助 :) 坚持下去! 不要忘记数组从索引 0 开始。尝试访问 studentScores[4] 会给你一个意想不到的数字。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-10
    • 2019-04-12
    • 2021-06-15
    • 1970-01-01
    • 2020-12-15
    • 2012-09-15
    相关资源
    最近更新 更多