描述:给出两个时间(24小时制),求第一个时间至少经过多久才能到达第二个时间,给出的时间有格式要求:x和y分别代表小时和分钟。0<=x<=24, 0<=y<=60。
输入:第一行为测试数据的组数T(1≤T≤50000)。请注意,任意两组测试数据之间是相互独立的。
每组数据包括两行:分别代表两个时间。
#include <iostream> #include<cstdio> #define ISHOUR(a) a>=0 && a<=24 ? true : false #define ISMINUTE(a) a>=0 && a<=60 ? true : false using namespace std; struct Stime{ int hour; int minute; }; int main() { int T; cin >> T; int temp; while(T--){ struct Stime time1; struct Stime time2; scanf("%d:%d %d:%d",&time1.hour,&time1.minute,&time2.hour,&time2.minute); while(ISHOUR(time1.hour)&&ISHOUR(time1.hour)&&ISMINUTE(time1.minute)&&ISMINUTE(time2.minute)){ if(time1.hour==time2.hour){ if(time1.minute > time2.minute) temp = 24*60 - (time1.minute - time2.minute); else temp = time2.minute - time1.minute; } else if(time1.hour > time2.hour){ temp = (24-time1.hour)*60-time1.minute+time2.hour*60+time2.minute; } else temp = (time2.hour-time1.hour)*60 - time1.minute+time2.minute; printf("%d",temp); break; } } return 0; }
后面这种更简单,是参考的其他人的答案。用第二个时间-第一个时间,即小时-小时;分钟-分钟;若结果<0,代表要经过一个新的24小时。
#include<iostream> #include<cstdio> using namespace std; struct STime{ int hour; int minute; }; int main(){ int N; while (scanf("%d", &N) != EOF){ for (int i = 0; i < N; i++){ STime time1, time2; scanf("%d:%d%d:%d", &time1.hour, &time1.minute, &time2.hour, &time2.minute); int temp = (time2.hour - time1.hour) * 60 + (time2.minute - time1.minute); //一开始的判断方式为:int result = (time2.hour - time1.hour) * 60 + (time2.minute - time1.minute) + (24 * 60)*(time1.hour < time2.hour ? 0 : 1);
//这样是错误的比如:00:40 00:02,不能只用小时相减结果判断 int result = temp + (24 * 60)*(temp < 0 ? 1 : 0); printf("%d ", result); } } system("pause"); return 0; }