【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 <stdio.h>
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 <math.h>

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 <math.h>

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;
}
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值