【C刷题记录】计算时间差

题目:
用结构体定义时钟类型,编程从键盘任意输入两个时间(例如4时55分和1时25分),计算并输出这两个时间之间的间隔。要求不输出时间差的负号。结构体类型定义如下:

typedef struct clock
{
    int hour;
    int minute;
    int second;
} CLOCK;

函数原型:

 CLOCK CalculateTime(CLOCK t1, CLOCK t2);

函数功能:计算并返回两个时间t1和t2之间的差
程序运行结果示例1:

Input time one:(hour,minute):4,55↙
Input time two: (hour,minute):1,25↙
3hour,30minute

程序运行结果示例2:

Input time one:(hour,minute):1,33↙
Input time two: (hour,minute):5,21↙
3hour,48minute

输入提示:
“Input time one:(hour,minute):”
“Input time two: (hour,minute):”
输入格式: “%d,%d”
输出格式:"%dhour,%dminute\n"

程序:
程序1.0

#include 
typedef struct clock
{
    int hour;
    int minute;
    int second;
}CLOCK;
CLOCK CalculateTime(CLOCK t1, CLOCK t2);

//要多麻烦有多麻烦的判断过程:)
CLOCK CalculateTime(CLOCK t1, CLOCK t2)
{
    CLOCK t3;
    if (t1.hour >= t2.hour)
    {
        t3.minute = t1.minute - t2.minute;
        if (t3.minute>=0)
            t3.hour = t1.hour - t2.hour;
        else
        {
            t3.hour = t1.hour - t2.hour - 1;//是-1嗷!
            t3.minute = 60 + t3.minute;//是60嗷!因为是富士所以是+嗷!
        }
    }
    else
    {
        t3.minute = t2.minute - t1.minute;
        if (t3.minute>=0)
            t3.hour = t2.hour - t1.hour;
        else
        {
            t3.hour = t2.hour - t1.hour - 1;
            t3.minute = 60 + t3.minute;
        }
    }
    return t3;
}

int main()
{
    CLOCK t1,t2,t3;
    printf( "Input time one:(hour,minute):");
    scanf("%d,%d",&t1.hour,&t1.minute);
    printf("Input time two: (hour,minute):");
    scanf("%d,%d",&t2.hour,&t2.minute);
    t3 = CalculateTime(t1, t2);
    printf("%dhour,%dminute\n", t3.hour, t3.minute);
    return 0;
}

程序2.0(只粘了计算部分)
也是先作差,再判断、调整
(记得要加#include

CLOCK CalculateTime(CLOCK t1, CLOCK t2)
{
    CLOCK t3;
    t3.hour = t1.hour - t2.hour;
    t3.minute = t1.minute - t2.minute;
    if (t3.hour < 0 && t3.minute < 0)
    {
        t3.minute = fabs(t3.minute);
        t3.hour = fabs(t3.hour);
    }
    else if (t3.hour < 0 || t3.minute < 0)
    {
        t3.minute = fabs(t3.minute);
        t3.hour = fabs(t3.hour);
        t3.hour = t3.hour - 1;
        t3.minute = 60 - t3.minute;
    }
    return t3;
}

程序3.0(只粘了计算部分)
简单粗暴直接转分钟算
(记得要加#include

CLOCK CalculateTime(CLOCK t1, CLOCK t2)
{
    CLOCK t3;
    t3.hour = (int)fabs(t1.hour * 60 + t1.minute - (t2.hour * 60 + t2.minute)) / 60;
	t3.minute = (int)fabs(t1.hour * 60 + t1.minute - (t2.hour * 60 + t2.minute)) % 60;
    return t3;
}

你可能感兴趣的:(【C刷题记录】计算时间差)