c語(yǔ)言怎么求兩個(gè)時(shí)間段之間的秒數(shù)

小億
145
2023-11-22 07:10:39

可以使用以下公式來(lái)計(jì)算兩個(gè)時(shí)間段之間的秒數(shù):

int calculateSeconds(int startHour, int startMinute, int startSecond, int endHour, int endMinute, int endSecond) {
    int totalSeconds = 0;
    
    // 計(jì)算起始時(shí)間的總秒數(shù)
    totalSeconds += startHour * 3600;      // 將小時(shí)轉(zhuǎn)換成秒數(shù)
    totalSeconds += startMinute * 60;      // 將分鐘轉(zhuǎn)換成秒數(shù)
    totalSeconds += startSecond;           
    
    // 計(jì)算結(jié)束時(shí)間的總秒數(shù)
    totalSeconds -= endHour * 3600;        // 將小時(shí)轉(zhuǎn)換成秒數(shù)
    totalSeconds -= endMinute * 60;        // 將分鐘轉(zhuǎn)換成秒數(shù)
    totalSeconds -= endSecond;
    
    // 如果總秒數(shù)為負(fù)數(shù),則代表結(jié)束時(shí)間比起始時(shí)間早,需要取絕對(duì)值
    if (totalSeconds < 0) {
        totalSeconds = abs(totalSeconds);
    }
    
    return totalSeconds;
}

使用示例:

int main() {
    int startHour, startMinute, startSecond;
    int endHour, endMinute, endSecond;
    
    printf("請(qǐng)輸入起始時(shí)間(時(shí) 分 秒):");
    scanf("%d %d %d", &startHour, &startMinute, &startSecond);
    
    printf("請(qǐng)輸入結(jié)束時(shí)間(時(shí) 分 秒):");
    scanf("%d %d %d", &endHour, &endMinute, &endSecond);
    
    int seconds = calculateSeconds(startHour, startMinute, startSecond, endHour, endMinute, endSecond);
    
    printf("兩個(gè)時(shí)間段之間的秒數(shù)為:%d\n", seconds);
    
    return 0;
}

這樣,用戶輸入起始時(shí)間和結(jié)束時(shí)間后,就可以得到兩個(gè)時(shí)間段之間的秒數(shù)。

0