Reputation: 1
It keeps giving me test1 /5 as an average score, i cant figure out what is wrong. Ive tried grouping the () differently, and all kinds of other stuff. I swear it worked a handful of times then just quit. Its now almost 1am and im still up trying to figure this simple code out.
For example: 60, 50, 80, 70, 80 gives me an avg of 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;
}
Upvotes: 0
Views: 73
Reputation: 493
the answers above are correct,
cin>> test1 >> test2 >> test3 >> test4 >> test5;
will not read the commas and will need space to enter the next value.
another solution to the suggested above:
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;
Upvotes: 1
Reputation: 206737
The answer by Joachim Pileborg has correctly diagnosed the problem and provides one solution to the problem. If you decide to keep the input to be comma separated, you could use:
char dummy;
cout << "Enter five test scores separated by commas: " << endl;
cin >> test1 >> dummy >> test2 >> dummy >> test3 >> dummy >> test4 >> dummy >> test5;
Upvotes: 2
Reputation: 409482
Here's your problem:
cout << "Enter five test scores separated by commas: " << endl;
cin >> test1 >> test2 >> test3 >> test4 >> test5;
The code doesn't read the commas. The input operator >>
separates on space.
That means that the input reads the first number, then expects another number but sees the comma instead and fails, not reading anything else.
So the simple solution is really to change the instruction output:
cout << "Enter five test scores separated by space: " << endl;
// ^^^^^
// Changed here
Upvotes: 8