Write a program that converts from 24-hour notation to 12-hour notation.
For example, it should convert 14:25 to 2:25 PM. The input is given as two integers.
There should be at least three functions, one for input, one to do the conversion, and one
for output. Record the AM/PM information as a value of type char, ’A’ for AM and ’P’
for PM. Thus, the function for doing the conversions will have a call-by-reference formal
parameter of type char to record whether it is AM or PM. (The function will have other
parameters as well.) Include a loop that lets the user repeat this computation for new
input values again and again until the user says he or she wants to end the program.
#include <iostream>
using namespace std;
void input(int& hours, int& minutes);
void output(int& hours, int& minutes, char& type);
void convert(int& hours, int& minutes, char& type);
int main()
{
int hours, minutes;
char type, ans;
do
{
input(hours, minutes);
convert(hours, minutes, type);
output(hours, minutes, type);
cout <<"Wanna do it again? (y/n):\n";
cin >> ans;
}
while (ans == 'y' || ans == 'Y');
return 0;
}
void input(int& hours, int& minutes)
{
while (hours > 23 && minutes > 59);
{
cout << "Enter the hours for the 24 hour time format:\n";
cin >> hours;
cout << "Enter the minutes for the 24 hour time format:\n";
cin >> minutes;
}
}
void output(int& hours, int& minutes, char& type)
{
cout << "The time converted to 12 hour format is:" << hours << ":";
cout.width(2);
cout.fill('0');
cout << minutes;
if (type == 'P')
{
cout << "P.M." << endl;
}
else
{
cout << "A.M." << endl;
}
}
void convert (int& hours, int& minutes, char& type)
{
if(hours < 12)
{
type = 'A';
}
else if (hours > 12)
{
hours = hours - 12;
type = 'P';
}
else
{
type = 'P';
}
}
No hay comentarios.:
Publicar un comentario