Register Now

Login

Lost Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Login

Register Now

Welcome to All Test Answers

C++ class that asks the user to enter three test scores and then displays the average of the scores


 

Download  file 

Not a member!
Create a FREE account here to get access and download this file 


 

TestScores Class
Design a TestScores C++ class that has member variables to hold three test scores. The
class should have a constructor, accessor, and mutator functions for the test score
fields, and a member function that returns the ave rage of the test scores. Demonstrate
the class by writing a separate program that creates an instance of the class. The program
should ask the user to enter three test scores, which are stored in the
TestScores object. Then the program should display the average of the scores. as
reported by the TestScores object.

Answer:


// TestScores Class
#include <iostream>
using namespace std;

// TestScores class declaration
class TestScores
{
private:
   int score1;  // Test score #1
   int score2;  // Test score #2
   int score3;  // Test score #3
   
public:
   // Default constructor
   TestScores()
      { score1 = 0; score2 = 0; score3 = 0; }
      
   // Constructor
   TestScores(int s1, int s2, int s3)
      { score1 = s1; score2 = s2; score3 = s3; }
   
   // Mutator functions
   void setScore1(int s)
      { score1 = s; }

   void setScore2(int s)
      { score2 = s; }

   void setScore3(int s)
      { score3 = s; }

   // Accessor functions
   int getScore1() const
      { return score1; }

   int getScore2() const
      { return score2; }

   int getScore3() const
      { return score3; }
   
   // The getAverage function returns
   // the average of the test scores.
   double getAverage() const
      { return (score1 + score2 + score3) / 3.0; }
};

int main()
{
   // Variable to hold a numeric value
   int value;
   
   // Create a TestScores object.
   TestScores myScores;
   
   // Get three test scores.
   cout << "Enter the first test score: "; cin >> value;
   myScores.setScore1(value);

   cout << "Enter the second test score: "; cin >> value;
   myScores.setScore2(value);

   cout << "Enter the third test score: "; cin >> value;
   myScores.setScore3(value);
   
   // Display the scores.
   cout << "\nHere are your test scores:\n"
        << "\tTest Score #1: " << myScores.getScore1() << endl
        << "\tTest Score #2: " << myScores.getScore2() << endl
        << "\tTest Score #3: " << myScores.getScore3() << endl
        << "\tAverage: " << myScores.getAverage() << endl;

   return 0;
}

About

Leave a reply

Captcha Click on image to update the captcha .

error: Content is protected !!