定义一个时间类Time,内有私有数据成员:hour,minute,second,另有成员函数:构造函数用于初始化数据成员,输出函数,运算符重载+(加号),。编写主函数:创建时间对象,再输入秒数 n,通过运算符重载+(加号),计算该时间再过 n 秒后的时间值,时间的表示形式为:时:分:秒,超过 24 时从 0 时重新开始计时。 测试输入包含若干测试用例,每个测试用例占一行。当读入0 0 0 0时输入结束,相应的结果不要输出。若输入的时、分、秒数据不合法,则输出:Time Error! n为非负整数,否则输出:Input n Error!
输入格式:
多行输入,每行以:小时 分 秒 n 的格式输入,读入0 0 0 0时输入结束 例如: 11 59 40 30 (表示时间为11:59:40,秒数n=30)
输出格式:
时间正确,则以“Time:时:分钟:秒”的格式输出时间 否则输出错误提示信息:Time Error! 或 Input n Error!
输入样例:
在这里给出一组输入。例如:
11 59 40 30
0 0 1 59
23 59 40 3011
24 23 40 34
20 69 45 45
10 23 100 34
10 23 34 -23
0 0 0 0
输出样例:
在这里给出相应的输出。例如:
Time:12:0:10
Time:0:1:0
Time:0:49:51
Time Error!
Time Error!
Time Error!
Input n Error!
#include <iostream>
using namespace std;
class Time {
private:
int hour;
int minute;
int second;
public:
void set(int h, int m, int s) {
hour = h;
minute = m;
second = s;
}
void display() {
cout << "Time:" << hour << ":" << minute << ":" << second << endl;
}
friend Time operator+(Time, int);
};
Time operator+(Time t, int n) {
t.second += n % 60;
// cout<<t.second<<endl;
if (t.second >= 60) {
t.second -= 60;
t.minute += 1;
}
// cout<<t.second<<endl;
t.minute += (n / 60) % 60;
if (t.minute >= 60) {
t.hour += 1;
t.minute -= 60;
}
t.hour += n / 60 / 60;
if (t.hour >= 24) {
t.hour -= 24;
}
return t;
}
int main() {
int a, b, c, d;
Time t;
cin >> a >> b >> c >> d;
do {
if ((a >= 0 && a < 24) && (b >= 0 && b < 60) && (c >= 0 && c < 60)) {
if (d >= 0) {
t.set(a, b, c);
} else {
cout << "Input n Error!" << endl;
cin >> a >> b >> c >> d;
continue;
}
} else {
cout << "Time Error!" << endl;
cin >> a >> b >> c >> d;
continue;
}
t = t + d;
t.display();
cin >> a >> b >> c >> d;
} while (!(a == 0 && b == 0 && c == 0 && d == 0));
}