Thursday, March 5, 2015

Post #5 - simple time conversion

Here's a simple program that converts an inputted time to 12-hr and 24-hr format. The user is supposed to enter the time in hours, minutes, and seconds as the time appears on his/her computer panel (keeping minutes and seconds separate - so 6:55 is entered as 6 hrs 50 min 5 sec).

#include <iostream>
using namespace std;

int main()

{ //Hours 0-24, Minutes and Seconds 0-60
int hours, minutes, seconds; 

cout << "Please input current time in hours, minutes, & seconds: ";
cin >> hours >> minutes >> seconds;
if (minutes == 60)
{ hours = hours + 1;
minutes = 0;
}
if (seconds == 60)
{ minutes = minutes + 1;
seconds = 0;
}
if (hours < 12) //Convert it to 24-hr

cout << fixed << showpoint;
cout << "\n12-hour clock: " << hours << ":" << minutes << ":" << seconds;
cout << "\n24-hour clock: " << hours + 12 << ":" << minutes << ":" << seconds;
}
else if (hours > 12) //Convert it to 12-hr
{
cout << fixed << showpoint;
cout << "\n12-hour clock: " << hours - 12 << ":" << minutes << ":" << seconds;
cout << "\n24-hour clock: " << hours << ":" << minutes << ":" << seconds;
}
else //Hour is 12:00 exactly
{
cout << fixed << showpoint;
cout << "\n12-hour clock: " << hours << ":" << minutes << ":" << seconds;
cout << "\n24-hour clock: " << hours << ":" << minutes << ":" << seconds;
}
cout << endl;
return 0;
}

I tested some output with the hours that provide an overlap between 12 and 24 format, when the hour is 11, 12, or 1.

Entered 11 23 09
12-hour clock: 11:23:9
24-hour clock: 23:23:9

Entered 12 45 13
12-hour clock: 12:45:13
24-hour clock: 12:45:13

Entered 1 56 60
12-hour clock: 1:57:0
24-hour clock: 13:57:0

Note that if hours is 60 or minutes is 60, the next unit higher resets to 0.  I wanted the program to print out leading zeroes or double zeroes to show this, but it only does trailing zeroes... need to find out how to print the leading ones too, so it will look better.

No comments:

Post a Comment