給定兩個時間 (時、分、秒),計算它們的和,正確處理**秒滿 60 進分、分滿 60 進時**。
numa b c d e f (第一組時間的時分秒 + 第二組時間的時分秒)x y z (時 分 秒)// 秒相加
z = c + f;
if (z >= 60) { y++; z -= 60; } // 或 z %= 60; y += z / 60;
// 分相加 (含秒進位)
y += b + e;
if (y >= 60) { x++; y -= 60; } // 或 y %= 60; x += y / 60;
// 時相加 (含分進位)
x += a + d;
// 時無上限 (題目未限制 24 小進位)
#includeint main() { int num; if (scanf("%d", &num) != 1) return 0; while (num--) { int a, b, c, d, e, f; scanf("%d %d %d %d %d %d", &a, &b, &c, &d, &e, &f); int x = a + d; int y = b + e; int z = c + f; // 秒進位 if (z >= 60) { y += z / 60; z %= 60; } // 分進位 if (y >= 60) { x += y / 60; y %= 60; } printf("%d %d %d", x, y, z); if (num > 0) putchar('\n'); } return 0; }
typedef struct {
int hour;
int min;
int sec;
} Time;
Time time_add(Time t1, Time t2) {
Time res;
res.sec = t1.sec + t2.sec;
res.min = t1.min + t2.min + res.sec / 60;
res.sec %= 60;
res.hour = t1.hour + t2.hour + res.min / 60;
res.min %= 60;
return res;
}
// 24 小制版本 (若需)
Time time_add_24h(Time t1, Time t2) {
Time res = time_add(t1, t2);
res.hour %= 24;
return res;
}
| 輸入 | 輸出 | 說明 |
|---|---|---|
| 1 10 20 30 2 30 40 50 | 3 51 20 | 30+50=80秒→1分20秒; 20+30+1=51分 |
| 1 0 59 59 0 0 2 | 1 0 1 | 59+2=61秒→1分1秒; 59+0+1=60分→1時0分 |
| 1 23 59 59 0 0 1 | 24 0 0 | 跨日 (若無 24h 模) |
if (z > 60) 而非 >= (60 秒須進位)int time_cmp(Time t1, Time t2) { // 回傳 1: t1>t2, 0: 相等, -1: t1 t2.hour ? 1 : -1;
if (t1.min != t2.min) return t1.min > t2.min ? 1 : -1;
if (t1.sec != t2.sec) return t1.sec > t2.sec ? 1 : -1;
return 0;
}
void time_print(Time t) {
printf("%02d:%02d:%02d", t.hour, t.min, t.sec);
}
時間加法是**進位制運算**的經典應用。掌握「個位進位 → 十位 → 百位...」的連續處理模式,同樣適用於日期計算、大數加法、多精度運算等場景。關鍵:用除法取商進位、取餘保留當前位,簡潔且不易出錯。