Thursday, December 31, 2015

Limbajul C++. Implementarea unei functionalitati aritmetice intr-o clasa

Exemplul urmator propus de programmr.com are un singur aspect netrivial: se cere ca initializarea membrilor clasei sa se faca prin metode, si nu prin explicitarea constructorilor.

Clasa student invocata in enunt are trei membri - un string care prezerva numele studentului, un integer pentru matricola si un tablou de intregi pentru notele la cinci materii.

O metoda publica input initializeaza membrii dupa instantierea unui obiect student. O alta metoda publica output afiseaza media notelor.

Enuntul original:

"A class student has three data members: name, roll, marks of 5 subjects and member functions to input name, roll no and marks, and display Percentage. Declare the class student and define the member functions. The program should ask user for name, roll no and marks in 5 subjects, and should display the percentage."

Codul si printscreen-ul:

#include<iostream>
#include <string>

using namespace std;
class student
{
    string name;
    int roll;
    int marks[5];
    public:
    student() : roll(0), name("John_Doe") 
    {
      for(int i = 0; i < 5; i++) marks[i] = 0;
    } 
    void input()
    {
        cout <<"\nName:";
        cin >> name;
        cout <<"Roll no:";
        cin >> roll;
        cout <<"Marks in 5 subjects:\n";
        for(int i = 0; i < 5; i++) cin >> marks[i];
    }
    void output()
    {
        cout <<"\nPercentage of student " << name <<": ";
        double percent = 0.0;
        for(int i = 0; i < 5; i++) percent += marks[i];
        cout << percent/5 <<"\n";
    }
    
};

int main()
{
            student s;
            cout <<"\nStudent not initialised.";
            s.output();
            cout <<"\nIntialising the student...\n";
            s.input();
            s.output();
            return 0;
}





No comments:

Post a Comment