Yêu cầu: Viết chương trình sử dụng struct để biểu diễn và hiển thị giờ, phút, giây và tính toán khoảng thời gian giữa 2 mốc thời gian(h/m/s)
Code:
/**************************************************************************/
#include <stdio.h>
#include <conio.h>
typedef struct
{
int h;
int m;
int s;
}TIME, *PTIME;
void importTime(PTIME time);
void dispTime(TIME time);
TIME calcTime(TIME time1, TIME time2);
void main()
{
TIME time1,time2,time;
//time1
importTime(&time1);
printf("\n(Time 1) ");
dispTime(time1);
//time2
importTime(&time2);
printf("\n(Time 2) ");
dispTime(time2);
// time = |tim1 - time2|;
printf("\n(Time 2 - Time 1) ");
time = calcTime(time1, time2);
dispTime(time);
getch();
}
/*****************************************************************
Description: - display time like hh:mm:ss
return : void
******************************************************************/
void dispTime(TIME time)
{
printf("hh:mm:ss = %.2d:%.2d:%.2d\n", time.h, time.m, time.s);
}
/*****************************************************************
Description: - import time
- save h,m,s to struct time
- return : void
******************************************************************/
void importTime(PTIME time)
{
int h,m,s;
printf("\nImport time:");
// Hour
do
{
printf("\nGio: ");
scanf("%d", &h);
} while (h < 0 || h > 23);
// Minute
do
{
printf("\nPhut: ");
scanf("%d", &m);
} while (m < 0 || m > 59);
// Sencond
do
{
printf("\nGiay: ");
scanf("%d", &s);
} while (s < 0 || s > 59);
//save this time to struct
time->h = h;
time->m = m;
time->s = s;
}
TIME calcTime(TIME time1, TIME time2)
{
int s1 = 0, s2 = 0;
int s;
TIME time;
s1 = 60*60*time1.h + 60*time1.m + time1.s;
s2 = 60*60*time2.h + 60*time2.m + time2.s;
s = s1 - s2;
if(s < 0)
{
s = (-1)*s;
}
time.m = s/60;
time.s = s%60;
time.h = time.m/60;
time.m = time.m%60;
return time;
}
Kết quả:
1 2 3 4 5 6 7 8 9 10 11 12 |
Import time: Gio: 12 Phut: 30 Giay: 25 (Time 1) hh:mm:ss = 12:30:25 Import time: Gio: 23 Phut: 15 Giay: 47 (Time 2) hh:mm:ss = 23:15:47 (Time 2 - Time 1) hh:mm:ss = 10:45:22 |
Leave a Reply