有两个时间段,以小时,分钟和秒的形式提供。然后计算它们的差。例如-
Time period 1 = 8:6:2 Time period 2 = 3:9:3 Time Difference is 4:56:59
给出了一个计算两个时间段之间的差异的程序,如下所示:
#include <iostream> using namespace std; int main() { int hour1, minute1, second1; int hour2, minute2, second2; int diff_hour, diff_minute, diff_second; cout << "Enter time period 1" << endl; cout << "Enter hours, minutes and seconds respectively: "<< endl; cin >> hour1 >> minute1 >> second1; cout << "Enter time period 2" << endl; cout << "Enter hours, minutes and seconds respectively: "<< endl; cin >> hour2 >> minute2 >> second2; if(second2 > second1) { minute1--; second1 += 60; } diff_second = second1 - second2; if(minute2 > minute1) { hour1--; minute1 += 60; } diff_minute = minute1 - minute2; diff_hour = hour1 - hour2; cout <<"Time Difference is "<< diff_hour <<":"<< diff_minute <<":"<<diff_second; return 0; }
输出结果
上面程序的输出如下-
Enter time period 1 Enter hours, minutes and seconds respectively: 7 6 2 Enter time period 2 Enter hours, minutes and seconds respectively: 5 4 3 Time Difference is 2:1:59
在上述程序中,以小时,分钟和秒的形式从用户接受了两个时间段。这在下面给出-
cout << "Enter time period 1" << endl; cout << "Enter hours, minutes and seconds respectively: "<< endl; cin >> hour1 >> minute1 >> second1; cout << "Enter time period 2" << endl; cout << "Enter hours, minutes and seconds respectively: "<< endl; cin >> hour2 >> minute2 >> second2;
然后使用以下代码段中提供的方法计算这两个时间段之间的差-
if(second2 > second1) { minute1--; second1 += 60; } diff_second = second1 - second2; if(minute2 > minute1) { hour1--; minute1 += 60; } diff_minute = minute1 - minute2; diff_hour = hour1 - hour2;
最后,显示时差。这在下面给出-
cout <<"Time Difference is "<< diff_hour <<":"<< diff_minute <<":"<<diff_second;