Answer to Question #189012 in C++ for Dunga

Question #189012
  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-08T17:56:00-0400
#include <iostream>
 
using namespace std;
 
class Time
{
public:
	Time() { h = 0, m = 0; }
	Time(int hours, int minutes);
	void AddMinutes(int minutes);
	void Display();
private:
	int h;
	int m;
};
 
Time::Time(int hours, int minutes)
{
	if (hours < 0) h = 0;
	else h = hours % 24;
	if (minutes < 0) m = 0;
	else m = minutes % 60;
}
 
void Time::AddMinutes(int minutes)
{
	if (m + minutes < 60) m += minutes;
	else
	{
		m = (m + minutes) % 60;
		h = (h + 1) % 24;
	}
} 
 
void Time::Display()
{
	cout << "Time: " << h / 10 << h % 10 << ":" << m / 10 << m % 10 << endl;
}
 
int main()
{
	Time list[4];
	list[0] = Time(23, 59);
	list[1] = Time(10, 30);
	list[2] = Time(12, 50);
	list[3] = Time(15, 30);
	for (int i = 0; i < 4; i++)
	{
		list[i].Display();
	}
	cout << "Add 15 minutes to all values" << endl;
	for (int i = 0; i < 4; i++)
	{
		list[i].AddMinutes(15);
		list[i].Display();
	}
	cout << endl;
	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
APPROVED BY CLIENTS