Write a class named testscores The class constructor should

Write a class named testscores. The class constructor should accept an array of rest scores as its argument., The class should have a member function that returns the average of the test scores. If any test score in the array is negative or greater than 100, the class should throw an exception. Demonstrate the class in a program.

Solution

#include <iostream>
#include <vector>
using namespace std;

class TestScores{
private:
    float total = 0; //intiialising total marks
    int length; //declaring variable for the size of scores array
    bool invalid = false;
public:
    TestScores(vector<float> scores){
        length = scores.size(); //length of vector of scores
        for(int i = 0; i<length; i++){
            if(scores[i]<0 || scores[i]>100){
                cout<<\"Error! Invalid test score!\"; //error for invalid input
                total = 0;
                invalid = true;
            }
            else{
                total+=scores[i];
            }
        }
    }

    float average(){
        if(invalid==true){
            return 0;
        }
        return this->total/this->length;
    }
};


int main(){
    vector<float> scores;
    scores.push_back(20);
    scores.push_back(25);
    scores.push_back(30);
    scores.push_back(35);
    scores.push_back(40);
    scores.push_back(455);
    scores.push_back(50);
    TestScores testScores = TestScores(scores);
    cout<<\"Average: \"<<testScores.average();
}

 Write a class named testscores. The class constructor should accept an array of rest scores as its argument., The class should have a member function that retu

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site