各位大侠帮帮忙吧 这道题用C++怎么做?

2024-12-21 22:05:14
推荐回答(2个)
回答1:

#include
using namespace std;

class Time
{
private:
int hour;
int minute;
int second;
public:
Time()
{
hour = 0;
minute = 0;
second = 0;
}
Time(int h, int m, int s)
{
hour = h;
minute = m;
second = s;
}
friend Time operator + (Time &t1, Time &t2);
friend Time operator - (Time &t1, Time &t2);
void display();
};

void Time::display()
{
cout << hour << ":" << minute << ":" << second << endl;
}

Time operator + (Time &t1, Time &t2)
{
Time t;
t.second = (t1.second + t2.second) % 60;
t.minute = (t1.minute + t2.minute + (t1.second + t2.second) / 60) % 60;
t.hour = (t1.hour + t2.hour + (t1.minute + t2.minute + (t1.second + t2.second) / 60) / 60) % 24;
return t;
}

Time operator - (Time &t1, Time &t2)
{
Time t;
t.second = (t1.second - t2.second + 60) % 60;
int m = 0;
if(t1.second < t2.second)
{
m = 1;
}
t.minute = (t1.minute - t2.minute - m + 60) % 60;
int h = 0;
if(t1.minute < t2.minute)
{
h = 1;
}
t.hour = (t1.hour - t2.hour - h + 24) % 24;
return t;
}

int main()
{
int h1, m1, s1, h2, m2, s2;

cout << "intput h1,m1,s1:" << endl;
cin >> h1 >> m1 >> s1;
cout << "intput h2,m2,s2:" << endl;
cin >> h2 >> m2 >> s2;

Time t1(h1, m1, s1);
Time t2(h2, m2, s2);
Time t = t1 + t2;

cout << "t1: ";
t1.display();
cout << "t2: ";
t2.display();
cout << "t1+t2: ";
t.display();

t = t1 - t2;
cout << "t1-t2: ";
t.display();

return 0;
}

回答2:

书上都有的啊