如何找到用户输入的平均值
How to find the average of user inputs
所以这是我的代码(去掉了标题,因为这是不相关的。
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
相关文章:
- 计算数组c++的平均值
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 2D数组来自文本输入,中间有空格
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 检查输入是否不是整数或数字
- 正在尝试了解输入验证循环
- 读取文件并输入到矢量中
- C++如何通过用户输入删除列表元素
- 用c++从输入文件中读取另一行
- C++击球平均值程序使用输入/输出文件打印名称,平均值,最高/最低平均值时遇到麻烦
- 如何将输入C 程序的平均值输入
- 如何找到用户输入的平均值
- 求向量c++的输入的平均值
- 从文件中获取输入并在其中存储平均值
- 找出用户在c++中输入的3个最大数字的平均值
- 查找输入值的平均值、最大值和最小值
- 寻找用户输入的几何平均值
- 如何取正输入的平均值,直到给定负输入
- C++循环查找用户输入的最小值、最大值、平均值和总和
- 从文件输入中查找双精度数组的平均值