【发布时间】: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 是的,这绝对是个问题。我能够编写一个程序,在没有函数的情况下平均分数,但作业需要一个,所以我尝试在其中扔一个,但我不知道如何与数组一起使用。