Answer to Question #189182 in C++ for BOKANG

Question #189182
  1. Create a class named Time that contains integer fields for hours and minutes. Store the hour in military time that is, 0 to 23. Add a function that displays the fields, using a colon to separate hours and minutes. (Make sure the minutes displays as two digits. For example, 3 o’clock should display at 3:00, not 3:0). Add another function that takes an argument that represents minutes to add to the time. The function updates the time based on the number of minutes added. For example, 12:30 plus 15 is 12:45, 14:50 plus 20 is 15:10, and 23:59 plus 2 is 0:01. The Time constructor ensures that the hour field is not greater than 23 and that the minutes field is not greater than 59; default to these maximum values if the arguments to the constructor are out of range. Create a main() function that instantiates an array of at least four Time objects and demonstrates that they display correctly both before and after varying amounts of time have been added to them.

 



1
Expert's answer
2021-05-04T17:55:39-0400
#include <iostream>
using namespace std;
class Time{
    int hours, minutes;
    public:
    Time(){}
    Time(int hrs, int min){
        hours = hrs;
        minutes = min;
        if(hours > 23) hours = 23;
        if(minutes > 59) minutes = 59;
    }
    void show(){
        cout<<this->hours<<":";
        if(this->minutes < 10) cout<<0;
        cout<<this->minutes<<endl;
    }
    Time add(int m){
        this->minutes += m;
        while(minutes >= 60){
            this->minutes -= 60;
            this->hours++;
        }
        while(this->hours > 23) this->hours -= 24;
        return *this;
    }
};
int main(){
    Time times[4] = {Time(23, 59), Time(24, 67), Time(0, 0), Time(3, 0)};
    for(int i = 0; i < 4; i++) times[i].show();
    cout<<endl;
    times[0].add(2).show();
    times[1].add(1).show();
    times[2].add(60).show();
    times[3].add(2881).show(); //added 48 hours and 1 minute
    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

Assignment Expert
05.05.21, 12:30

Dear Bokang, Questions in this section are answered for free. We can't fulfill them all and there is no guarantee of answering certain question but we are doing our best. And if answer is published it means it was attentively checked by experts. You can try it yourself by publishing your question. Although if you have serious assignment that requires large amount of work and hence cannot be done for free you can submit it as assignment and our experts will surely assist you.

Bokang
05.05.21, 05:54

Could you please explain from line 13 to 26

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS