天天看點

nextSec()擷取下一秒的四種寫法

題目:輸入一個24小時制時間HH:MM:SS,輸出它的下一秒。

時間結構體定義:

typedef struct
{
    int h;
    int m;
    int s;
} time;
           

輸入時間到變量:

void getT(time *t)
{
    scanf("%d:%d:%d", &t->h, &t->m, &t->s);
}
           

輸出時間:

void printT(time t)
{
    printf("%02d:%02d:%02d", t.h, t.m, t.s);
}
           

擷取下一秒:

time nextSec(time t)
{
    if (t.s < 59)
        t.s++;
    else if (t.m < 59)
        t.m++, t.s = 0;
    else if (t.h < 23)
        t.h++, t.m = t.s = 0;
    else
        t.h = t.m = t.s = 0;
    return t;
}
           

擷取下一秒的另一種寫法:

time nextSec2(time t)
{
    if (t.s < 59)
        t.s++;
    else
    {
        t.s = 0;
        if (t.m < 59)
            t.m++;
        else
        {
            t.m = 0;
            if (t.h < 23)
                t.h++;
            else
                t.h = 0;
        }
    }
    return t;
}
           

擷取下一秒的第三種寫法:

time nextSec3(time t)
{
    if (t.s == 59)
        if (t.m == 59)
            if (t.h == 23)
                t.h = t.m = t.s = 0;
            else
                t.h++, t.m = t.s = 0;
        else
            t.m++, t.s = 0;
    else
        t.s++;
    return t;
}
           

擷取下一秒的第四種寫法:

time nextSec4(time t)
{
    if (t.s == 59)
    {
        t.s = 0;
        if (t.m == 59)
        {
            t.m = 0;
            if (t.h == 23)
                t.h = 0;
            else
                t.h++;
        }
        else
            t.m++;
    }
    else
        t.s++;
    return t;
}
           

主函數:

int main()
{
    time t;
    getT(&t);
    printT(nextSec(t));
}
           

繼續閱讀