SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Walter Savitch ,kenrick Mock
Chapter:
Structures And Classes
Exercise:
Programming Projects
Question:8 | ISBN:9780132846813 | Edition: 5

Question

Define a class named Money that stores a monetary amount. The class should have two private integer variables, one to store the number of dollars and another to store the number of cents. Add accessor and mutator functions to read and set both member variables. Add another function that returns the monetary amount as a double. Write a program that tests all of your functions with at least two different Money objects.


TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

C++ program code:

#include <iostream>
using namespace std;
//Create a class name, 
class Money 
{
private:
    //Declare variables
    int dollars;
    int cents;

public:
    //Default constructor
    Money()
    {
        dollars = 0;
        cents = 0;
    }
     //Accessor functions getDollars and getCents 
     //are defined to retrieve the values of dollars and cents.
    int getDollars() const {
        return dollars;
    }

    int getCents() const {
        return cents;
    }
    //Mutator functions setDollars and setCents are
    //defined to set the values of dollars and cents.
    void setDollars(int value) {
        dollars = value;
    }

    void setCents(int value) {
        cents = value;
    }
    //The getAmount function returns the monetary amount as a 
    //double by adding dollars to cents divided by 100.
    double getAmount() const {
        return dollars + (static_cast<double>(cents) / 100);
    }
};
//Program begins with a main method
int main() 
{
    // two Money objects are created, money1 and money2.
    Money money1;
    money1.setDollars(10);
    money1.setCents(50);
    //Call the methods and display appropriate output
    cout << "Money 1: $" << money1.getDollars() << "." << money1.getCents() << endl;
    cout << "Amount 1: " << money1.getAmount() << endl;

    Money money2;
    money2.setDollars(5);
    money2.setCents(75);

    cout << "Money 2: $" << money2.getDollars() << "." << money2.getCents() << endl;
    cout << "Amount 2: " << money2.getAmount() << endl;

    return 0;
}

Output of the program code:

Money 1: $10.50
Amount 1: 10.5
Money 2: $5.75
Amount 2: 5.75

 

0 0

Discussions

Post the discussion to improve the above solution.