这是一个课程的作业,我几乎到了我想要的地方,只是想要一些关于最佳方法的建议。
用户将以24小时格式输入时间,以小时和分钟为单位输入延迟时间。我必须在延迟结束时以AM / PM格式计算和显示时间。我必须使用函数,不能使用全局变量。我还需要在为小时部分输入999时退出条件。
基本上,我正在尝试决定继续计算延迟的最佳方法。我尝试了几种不同的方法,但是,对它们中的任何一种都没有真正的满意。现在,程序只是循环询问小时,分钟和延迟,直到我能够决定最佳的继续方式。
#include <iostream>
using namespace std;
//Function Prototypes
void convert(int&, int&, int&, char&);
void output(int&, int&, char&);
int main()
{
int hours, minutes, delay;
char ampm;
cout<<"Enter the value for Hours (999 to quit): "<<endl;
cin >> hours;
while (hours != 999)
{
cout << "Enter minutes: ";
cin >> minutes;
cout << "Enter delay: ";
cin >> delay;
cout<<"Enter the value for Hours (999 to quit): "<<endl;
cin >> hours;
}
return 0;
}
void convert(int& hours, int& minutes, int& delay, char& ampm)
{
if(hours > 12)
{
hours = hours - 12;
ampm = 'p';
}
else if(hours == 12) ampm = 'p';
else ampm = 'a';
}
void output(int& hours, int& minutes, char& ampm)
{
if(ampm == 'p')
{
(minutes < 10); cout << hours << ":0" << minutes << " P.M.";
cout << hours << ":" << minutes << " P.M.";
}
else
{
(minutes < 10); cout << hours << ":0" << minutes << " A.M.";
cout << hours << ":" << minutes << " A.M.";
}
}
答案 0 :(得分:0)
我希望它有所帮助。我试图让它保持干净简洁。
#include <iostream>
#include <string>
using namespace std;
//Function Prototypes
void convert(int&, int&, int&, string&);
void output(int&, int&, string&);
int main()
{
int hours, minutes, delay;
string ampm;
cout << "Enter hours(0-24): ";
cin >> hours;
do{
cout << "Enter minutes: ";
cin >> minutes;
cout << "Enter delay(in minutes): ";
cin >> delay;
convert(hours, minutes, delay, ampm);
output(hours, minutes, ampm);
cout << endl << "Enter the value for Hours (999 to quit): ";
cin >> hours;
} while (hours != 999);
return 0;
}
void convert(int& hours, int& minutes, int& delay, string& ampm)
{
int temp = 0;
minutes += delay;
if (minutes > 60) {
temp = minutes / 60;
hours += temp;
minutes = minutes - temp * 60;
}
if (hours > 12){
hours -= 12;
ampm = "PM";
}
else {
ampm = "AM";
}
}
void output(int& hours, int& minutes, string& ampm)
{
if (minutes > 0 && minutes < 10) {
cout << hours << ":0" << minutes << " " << ampm << endl;;
}
else if (minutes == 0) {
cout << hours << ":0" << minutes << " " << ampm << endl;;
}
else {
cout << hours << ":" << minutes << " " << ampm << endl;
}
}