如何找到用户输入的平均值

How to find the average of user inputs

本文关键字:平均值 输入 用户 何找      更新时间:2023-10-16

所以这是我的代码(去掉了标题,因为这是不相关的。

int main() {
float program = 0;
float scores = 0;
float test = 0;
float testScores = 0;
float e = 1;
float exam = 0;
float programAverage = 0;
cout << "Enter the number of assignments that were graded: ";
cin >> program;
for (int i = 1; i <= program; i++){
  cout << "Enter the score for assignment # " << i <<": "; cin >> scores;
}
  cout << "Enter the number of test: ";
  cin >> test;
for (int e = 1; e <= test; e++){
  cout << "Enter the score for test # " << e << ": "; cin >> testScores;
}
  cout << "Enter the final exam score: ";
  cin >> exam;
  programAverage = (scores/program);
  cout << "Program Average: " << programAverage << endl;
}

最后一部分我遇到了问题,因为每当我编译程序时,编译器只会记住用户输入的最后一个数字,而不会对其进行平均。如何让它将所有用户输入数字相加然后求平均值?

int main() {
float program = 0;
float scores = 0;
float test = 0;
float testScores = 0;
float e = 1;
float exam = 0;
float programAverage = 0;
float scoresSum = 0; // variable that adds up all the input scores
cout << "Enter the number of assignments that were graded: ";
cin >> program;
for (int i = 1; i <= program; i++){
  cout << "Enter the score for assignment # " << i <<": "; cin >> scores;
  scoresSum += scores; // adds up all the scores
}

  cout << "Enter the number of test: ";
  cin >> test;
for (int e = 1; e <= test; e++){
  cout << "Enter the score for test # " << e << ": "; cin >> testScores;
}
  cout << "Enter the final exam score: ";
  cin >> exam;
  programAverage = (scoresSum/program); // divide the total score out of program number
  cout << "Program Average: " << programAverage << endl;
}

所以问题是你没有把输入分数加起来。变量"scores"只有最后一个输入分数的值。您必须设置一个变量来汇总到目前为止的所有输入分数,例如代码中的 scoresSum。并在每次提交分数时将分数相加。

您可以通过查看带有注释的行轻松找到您的代码和我的代码之间的区别。

float _sum=0;
for (int i = 1; i <= program; i++){
  cout << "Enter the score for assignment # " << i <<": "; cin >> scores;
_sum+=i;
}
  programAverage = (_sum/program);
  cout << "Program Average: " << programAverage << endl;
嗯,

是的,因为这个循环,scores总是输入最后一个值:

for (int i = 1; i <= program; i++){
  cout << "Enter the score for assignment # " << i <<": "; cin >> scores;
}

平均值定义为总和除以实例数。您不是求和,只是在执行cin >> scores时不断用最后一个读取值覆盖"分数"。因此,问题可以重述为"我如何对用户输入的所有数字求和?计算机完全按照您的指示进行操作,您需要弄清楚如何准确地告诉它以汇总所有输入的scores

那么,在现实生活中你会怎么做呢?你可以记录所有的分数,也许可以用计算器将它们相加。首先初始化计数:

double sum = 0.0;

然后在"cout <<"输入分数......"的行之后。您加到总和:

sum = sum + scores;

或者C++有方便的速记符号

sum += scores