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

时间:2014-02-20 01:38:04

标签: c++

所以这是我的代码(剥离标题,因为这是不可靠的。)

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;
}

最后一部分我遇到了问题,因为每当我编译程序时,编译器只会记住用户输入的最后一个数字而不是平均值。如何才能将所有用户输入数字加在一起然后平均?

3 个答案:

答案 0 :(得分:1)

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;

答案 1 :(得分:1)

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;
}

所以问题是你没有加上输入分数。 变量“得分”仅具有最后输入得分的值。 您必须设置一个变量来总结到目前为止的所有输入分数,例如代码中的scoresSum。 并在每次提交分数时加分。

通过查看带注释的行,您可以轻松找到代码与我的代码之间的差异。

答案 2 :(得分:0)

好吧,因为这个循环,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&lt;&lt; “输入分数......”你加上总和:

sum = sum + scores;

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

sum += scores
相关问题