酷代码 AI
菜单
服务商

C++ 实现:精准计算小 X 从入睡到闹钟响的睡眠时间

```cpp #include <iostream> using namespace std; int main() { int h1, m1, s1; int h2, m2, s2; // 输入闹钟响的时刻 cin >> h1 >> m1 >> s1; // 输入睡觉的时刻 cin >> h2 >> m2 >> s2; // 将时刻都转换为秒 int totalSeconds1 = h1 * 3600 + m1 * 60 + s1; int totalSeconds2 = h2 * 3600 + m2 * 60 + s2; int sleepSeconds; // 判断是否跨天 if (totalSeconds1 >= totalSeconds2) { sleepSeconds = totalSeconds1 - totalSeconds2; } else { sleepSeconds = 24 * 3600 - totalSeconds2 + totalSeconds1; } // 计算小时、分钟和秒 int h = sleepSeconds / 3600; int m = (sleepSeconds % 3600) / 60; int s = sleepSeconds % 60; // 输出结果 cout << h << " " << m << " " << s << endl; return 0; } ``` 代码解释: 1. 输入处理:通过`cin`读取闹钟响的时刻`h1, m1, s1`和睡觉的时刻`h2, m2, s2`。 2. 转换为秒:将时刻转换为秒,便于计算。`totalSeconds1`表示闹钟响的时刻对应的总秒数,`totalSeconds2`表示睡觉时刻对应的总秒数。 3. 计算睡觉总秒数:判断是否跨天,如果闹钟响的时刻晚于睡觉时刻,直接相减;否则,需要加上一天的秒数。 4. 计算小时、分钟和秒:通过除法和取模运算,将总秒数转换为小时、分钟和秒。 5. 输出结果:将计算得到的小时、分钟和秒输出。 ######[AI问答 | 488点数解答 | 2025-11-10 18:42:04]

相关提问
本站限时免费提问中
实用工具查看更多
Linux在线手册 [开发类]
Jquery在线手册 [开发类]
今日油价 [生活类]
图片互转base64 [开发类]
时间转换器 [开发类]