AVerage help
Dec 11, 2012 at 4:15pm UTC
I'm trying to get the average of 3 test scores in the code below but it won't work, how do I go about doing it?
1 2 3 4 5 6 7 8 9 10 11
friend std::ostream &operator <<(std::ostream &out, const Grade &s)
{
return out << "Name: " << s.first << " " << s.middle << " " << s.last << std::endl
<< "test1: " << s.test1 << std::endl
<< "test2: " << s.test2 << std::endl
<< "test3: " << s.test3 << std::endl
<< "average: " << s.test1+s.test2+s.test3/3 << std::endl
<< "Absences: " << s.absence << std::endl;
}
};
Dec 11, 2012 at 4:22pm UTC
You have to put parenthesis, same as in math.
( s.test1+s.test2+s.test3) /3
Dec 11, 2012 at 4:23pm UTC
ok i do that and i get this error, heres my code:
error C2676: binary '/' : 'std::basic_string<_Elem,_Traits,_Ax>' does not define this operator or a conversion to a type acceptable to the predefined operator
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
#include <iostream>
#include <ctime>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
struct Grade
{
std::string last,
first,
middle,
test1,
test2,
test3,
absence;
friend std::istream &operator >>(std::istream &in, Grade &s)
{
return in >> s.last >> s.first >> s.middle >> s.test1 >> s.test2 >> s.test3 >> s.absence;
}
friend std::ostream &operator <<(std::ostream &out, const Grade &s)
{
return out << "Name: " << s.first << " " << s.middle << " " << s.last << std::endl
<< "test1: " << s.test1 << std::endl
<< "test2: " << s.test2 << std::endl
<< "test3: " << s.test3 << std::endl
<< "average: " << (s.test1+s.test2+s.test3)/3 << std::endl
<< "Absences: " << s.absence << std::endl;
}
};
void main ()
{
std::vector<Grade> grades;
{
std::ifstream infile ("students.txt" );
Grade temp;
while (infile >> temp)
{
grades.push_back(temp);
}
}
for (size_t i = 0; i < grades.size(); ++i)
{
std::cout << grades[i] << std::endl;
}
}
Dec 11, 2012 at 4:27pm UTC
The test variables are strings. You can't divide a string. You probably want to make them some numerical type instead of string.
Dec 11, 2012 at 4:29pm UTC
How?
Dec 11, 2012 at 4:33pm UTC
1 2 3 4 5 6 7 8 9 10
struct Grade
{
std::string last,
first,
middle,
absence;
double test1,
test2,
test3;
...
Last edited on Dec 11, 2012 at 4:34pm UTC
Dec 11, 2012 at 4:36pm UTC
Topic archived. No new replies allowed.