天天看点

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));
}
           

继续阅读