[PTA]7-126 时间差 (10分)

该程序旨在读取两个24小时制的时间,并计算它们之间的时间差,输出相差的小时和分钟数。确保第二个时间晚于或等于第一个时间,且都在同一天内。例如,从10:30到11:45,时间差为1小时15分钟。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

10点半到11点45之间,有几小时几分钟呢?

你要写一个程序,读入两个时间,计算它们之间的时间差,输出相差几小时几分钟。

输入
输入两个时间,均以24小时制表达,每个时间以“小时:分钟”的形式表达,第二个时间一定比第一个时间晚或相同,而且一定在同一天内。

输出
输出表示两个时间之间的时间差的两个数字,第一个数字是时间差中的小时数,第二个数字是时间差中的分钟数。

输入例子
10:30 11:45

输出例子
1 15

#include<stdio.h>
int main()
{
   
   
    int h1=0,m1=0,h2=
### PTA 7-2 时间类 C++ 实现解决方案 在C++中实现时间类,通常需要定义一个类来表示时间,并提供相应的构造函数、成员函数和运算符重载功能。以下是一个可能的实现方案,基于常见的需求,例如时间的加减操作、格式化输出等。 #### 类设计 时间类的设计可以包括以下部: 1. **私有成员变量**:用于存储小时、钟和秒。 2. **公有成员函数**:包括构造函数、设置时间的函数、获取时间的函数、时间的加减操作以及格式化输出。 3. **运算符重载**:支持时间的加法和减法操作。 以下是完整的C++代码实现: ```cpp #include <iostream> #include <iomanip> using namespace std; class Time { private: int hour; int minute; int second; // 辅助函数:规范化时间 void normalize() { if (second >= 60) { minute += second / 60; second %= 60; } if (minute >= 60) { hour += minute / 60; minute %= 60; } if (hour >= 24) { hour %= 24; } } public: // 构造函数 Time(int h = 0, int m = 0, int s = 0) : hour(h), minute(m), second(s) { normalize(); } // 设置时间 void setTime(int h, int m, int s) { hour = h; minute = m; second = s; normalize(); } // 获取时间 void getTime(int &h, int &m, int &s) const { h = hour; m = minute; s = second; } // 格式化输出 void printTime() const { cout << setfill('0') << setw(2) << hour << ":" << setw(2) << minute << ":" << setw(2) << second; } // 运算符重载:时间相加 Time operator+(const Time &other) const { int totalSeconds = this->hour * 3600 + this->minute * 60 + this->second + other.hour * 3600 + other.minute * 60 + other.second; return Time(totalSeconds / 3600, (totalSeconds % 3600) / 60, totalSeconds % 60); } // 运算符重载:时间相减 Time operator-(const Time &other) const { int totalSeconds = this->hour * 3600 + this->minute * 60 + this->second - (other.hour * 3600 + other.minute * 60 + other.second); if (totalSeconds < 0) { totalSeconds += 24 * 3600; // 确保结果为正值(同一天内) } return Time(totalSeconds / 3600, (totalSeconds % 3600) / 60, totalSeconds % 60); } }; int main() { int h1, m1, s1, h2, m2, s2; cin >> h1 >> m1 >> s1 >> h2 >> m2 >> s2; Time t1(h1, m1, s1); Time t2(h2, m2, s2); Time sum = t1 + t2; Time diff = t1 - t2; cout << "Sum: "; sum.printTime(); cout << endl; cout << "Difference: "; diff.printTime(); cout << endl; return 0; } ``` #### 解释 1. **`normalize` 函数**:确保时间的小时、钟和秒都在合理范围内[^1]。 2. **构造函数与 `setTime` 方法**:初始化或修改时间值,并调用 `normalize` 确保合法性。 3. **`printTime` 方法**:以固定宽度格式化输出时间,便于阅读。 4. **运算符重载**:通过将时间转换为总秒数进行加减操作,简化计算逻辑[^2]。 #### 注意事项 - 如果输入的时间超出合法范围(如钟大于59),需通过 `normalize` 函数调整。 -时间相减时,若结果为负值,则假设时间为同一天内,因此加上24小时的总秒数[^3]。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值