Answer to Question #319430 in C++ for sds

Question #319430

cause the program to print out the total cars and total cash and then exit. *3. Create a class called time that has separate int member data for hours, minutes, and seconds. One constructor should initialize this data to 0, and another should initialize it to fixed values. Another member function should display it, in 11:59:59 format. The final member function should add two objects of type time passed as arguments. A main() program should create two initialized time objects (should they be const?) and one that isn’t initialized. Then it should add the two initialized values together, leaving the result in the third time variable. Finally it should display the value of this third variable. Make appropriate member functions const


1
Expert's answer
2022-03-28T08:03:24-0400
#include <iostream>
#include <iomanip>
using namespace std;


class Time {
    int hours;
    int minutes;
    int seconds;


public:
    Time();
    Time(int h, int m, int s);
    void display() const;
    Time add(Time& t) const;
};


Time::Time() 
    : hours(0), minutes(0), seconds(0)
{}


Time::Time(int h, int m, int s) 
    : hours(h), minutes(m), seconds(s)
{}


void Time::display() const {
    cout << setfill('0') << hours%12 << ':'
         << setw(2) << minutes << ':' << setw(2) << seconds 
         << (hours >= 12? " pm" : " am") << endl;
}


Time Time::add(Time& t) const {
    int h=0, m=0, s=0;


    s = seconds + t.seconds;
    if (s >= 60) {
        s -= 60;
        m = 1;
    }

    m += minutes + t.minutes;
    if (m >=60) {
        m -= 60;
        h = 1;
    }
    
    h += hours + t.hours;
    if (h >= 24) {
        h -= 24;
    }
    return Time(h, m, s);
}


int main() {
    Time t1(9, 30, 0);
    Time t2(2, 45, 5);
    Time t3;

    t3 = t1.add(t2);
    t3.display();

    return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog