编写程序,根据火车的出发时间和达到时间计算整个旅途所用的时间。 【输入】 在一行中给出两个正整数,其间以空格分隔,分别表示火车的出发时间和到达时间。每个时间的格式为两位小时数(00~23)和两位分钟数(00~59),假设出发和到达在同一天内。 【输出】 在一行中输出该旅途所用的时间,格式为“hh:mm”,其中hh为两位小时数、mm为两位分钟数。 【输入示例】 1201 1530 【输出示例】 03:29 【提示】 #include <iomanip> 设置小时hour的输出宽度和填充字符: cout << setw(2) << setfill('0') << hour << endl;
时间: 2023-03-20 12:00:50 浏览: 183
以下是一个Python编写的程序示例,可以根据输入的火车出发时间和到达时间计算整个旅途所用的时间,并输出格式为“hh:mm”的结果:
```python
start_time, end_time = input().split() # 读取输入的出发时间和到达时间
start_hour, start_minute = map(int, [start_time[:2], start_time[2:]]) # 分离出发时间的小时和分钟
end_hour, end_minute = map(int, [end_time[:2], end_time[2:]]) # 分离到达时间的小时和分钟
if end_minute < start_minute: # 处理到达时间的分钟小于出发时间的分钟的情况
end_minute += 60
end_hour -= 1
total_minute = (end_hour - start_hour) * 60 + (end_minute - start_minute) # 计算总共用时的分钟数
total_hour, total_minute = divmod(total_minute, 60) # 将总共用时的分钟数转化为小时数和分钟数
print('{:02d}:{:02d}'.format(total_hour, total_minute)) # 输出结果
```
该程序首先使用`input().split()`读取输入的出发时间和到达时间,然后使用`map(int, [start_time[:2], start_time[2:]])`和`map(int, [end_time[:2], end_time[2:]])`分别将出发时间和到达时间的小时和分钟分离出来,并将它们转化为整数类型。
接下来,程序根据到达时间的分钟数是否小于出发时间的分钟数来进行判断和处理。如果是,说明到达时间跨越了一个小时,需要将到达时间的分钟数加上60,并将到达时间的小时数减去1。
最后,程序使用`(end_hour - start_hour) * 60 + (end_minute - start_minute)`计算总共用时的分钟数,并使用`divmod(total_minute, 60)`将总共用时的分钟数转化为小时数和分钟数。最后使用`'{:02d}:{:02d}'.format(total_hour, total_minute)`将小时数和分钟数格式化为“hh:mm”的形式,并输出结果。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)