它一直给我test1 / 5作为平均分,我无法弄清楚出了什么问题。香港专业教育学院尝试过不同的分组,以及各种其他东西。我发誓它工作了几次然后就退出了。它现在差不多凌晨1点了,我还在努力想出这个简单的代码。
例如:60,50,80,70,80给我平均12(test1 / 5)
#include <iostream>
#include <string>
using namespace std;
double testAvgCal(double, double, double, double, double, double&);
void printing(double);
int main()
{
double test1 = 0;
double test2 = 0;
double test3 = 0;
double test4 = 0;
double test5 = 0;
double testAvg = 0;
cout << "Enter five test scores separated by commas: " << endl;
cin >> test1 >> test2 >> test3 >> test4 >> test5;
testAvgCal(test1, test2, test3, test4, test5, testAvg);
printing(testAvg);
}
double testAvgCal(double test1, double test2, double test3, double test4, double test5, double& testAvg)
{
testAvg = (test1 + test2 + test3 + test4 + test5)/ 5;
return testAvg;
}
void printing(double testAvg)
{
cout << "The test score average of this student is: " << testAvg << endl;
}
答案 0 :(得分:8)
这是你的问题:
cout << "Enter five test scores separated by commas: " << endl;
cin >> test1 >> test2 >> test3 >> test4 >> test5;
代码没有读取逗号。输入操作符>>
在空间上分隔。
这意味着输入读取第一个数字,然后期望另一个数字但是看到逗号而失败,而不是读取任何其他数字。
所以简单的解决方案就是改变指令输出:
cout << "Enter five test scores separated by space: " << endl;
// ^^^^^
// Changed here
答案 1 :(得分:2)
The answer by Joachim Pileborg已正确诊断出问题,并为问题提供了一种解决方案。如果您决定将输入保持为逗号分隔,则可以使用:
char dummy;
cout << "Enter five test scores separated by commas: " << endl;
cin >> test1 >> dummy >> test2 >> dummy >> test3 >> dummy >> test4 >> dummy >> test5;
答案 2 :(得分:1)
上面的答案是正确的,
cin>> test1 >> test2 >> test3 >> test4 >> test5;
不会读取逗号,并且需要空格才能输入下一个值。
上述建议的另一种解决方案:
double total = 0;
double testScore;
int totalNuberOfTests = 5; //can be changed to whatever you want
for (int i = 0; i< totalNuberOfTests ; i++)
{
cout<<"Eneter score for Test # "<<i+1<<": ";
cin>>testScore;
total += testScore;
}
double testAverage = total/totalNuberOfTests;