Hi, trying to make a class with some member functions that basically just gathers a name from the declaration and allows you to add_quiz(int score) and get the average. The only issue is, since I'm dividing two integers, I'm getting flat .00 doubles as output. Should I change the divisor or dividend to a double to fix this? Also I'm having issues getting the get_name() member function to work correctly, when I call it I get no output. Is there something different I need to do with the class constructor? Thanks in advance for any help.
#include <iostream>
#include <string>
#include <iomanip>
usingnamespace std;
class Student
{
public: //public interface
/**Constructor that initializes an object with private data member 'string name = "name"'
* @param name >> Student's name
*/
Student(string name);
/**Function that returns the name of the student in the given object
* @return name >> Student's name
*/
string get_name() const;
/**Adds a quiz to the score total and increments the amount of quizzes submitted
* @param score >> quiz score
*/
void add_quiz(int score);
/**Returns the total score of all quizes for the particular object
* @return total_score >> sum of all quiz scores
*/
int get_total_score() const;
/**Returns average score of all quizzes
* @return average >> average quiz score as double
*/
double get_avg_score() const;
private: //private data members
string name;
int total_score = 0;
int number_of_quizzes = 0;
};
Student::Student(string name)
{
total_score = 0;
number_of_quizzes = 0;
}
void Student::add_quiz(int score)
{
number_of_quizzes++;
total_score += score;
}
string Student::get_name() const
{
return name;
}
int Student::get_total_score() const
{
return total_score;
}
double Student::get_avg_score() const
{
double average = total_score / number_of_quizzes;
return average;
}
int main()
{
Student steve("Steve");
Student karen("Karen");
steve.add_quiz(90);
steve.add_quiz(95);
steve.add_quiz(84);
steve.add_quiz(49);
int totscore = steve.get_total_score();
double avgscore = steve.get_avg_score();
cout << "Total of all " << steve.get_name() << "'s Test Scores: " << totscore << endl;
cout << fixed << setprecision(2) << steve.get_name() << "'s Average Quiz Score: " << avgscore << endl;
return 0;
}
This gives me an output of
Total of all 's Test Scores: 318
's Average Quiz Score: 79.00
The only issue is, since I'm dividing two integers, I'm getting flat .00 doubles as output. Should I change the divisor or dividend to a double to fix this?
Yes.
Also I'm having issues getting the get_name() member function to work correctly, when I call it I get no output. Is there something different I need to do with the class constructor?
You're accepting an std::string in the constructor, but you're not doing anything with it. The language isn't going to assign that value to a member just because you gave the formal parameter the same name as the class member. You need to actually perform the initialization.