69,382
社区成员
发帖
与我相关
我的任务
分享
#include <stdio.h>
#include <math.h>
struct flight
{
char * departure;
char * arriving;
unsigned int minutes;
};
/* Search for the appropriate flight and return its pointer.
* This function will find out the most close time's flight compare
* to the given value of minutes.
* @flights: the struct flight
* @num: the number of flights
* @value: the given value of minutes
*/
struct flight * search(struct flight * flights, unsigned int num, unsigned int value)
{
int i,last_diff=32767,diff;
struct flight * prev = NULL;
struct flight * cur = flights;
/*printf("func:search,value:%d\n",value);*/
for(i = 0; i < num; i++) {
diff = abs(cur->minutes - value);
/*printf("func:search,last_diff:%d,diff:%d\n",last_diff,diff);*/
if(last_diff < diff)
return prev;
last_diff = diff;
prev = cur;
cur++;
}
return prev;
}
int main(void)
{
unsigned int hour,minute,value;
struct flight * result = NULL;
struct flight flights[8] = {
"8:00 a.m.", "10:16 a.m.", 480,
"9:43 a.m.", "11:52 a.m.", 583,
"11:19 a.m.", "1:31 p.m.", 679,
"12:47 p.m.", "3:00 p.m.", 767,
"2:00 p.m.", "4:08 p.m.", 840,
"3:45 p.m.", "5:55 p.m.", 945,
"7:00 p.m.", "9:20 p.m.", 1140,
"9:45 p.m.", "11:58 p.m.", 1305
};
system("cls");
printf("Enter a 24-hour time: ");
scanf("%d:%d",&hour,&minute);
value = hour * 60 + minute;
result = search(flights,8,value);
printf("Closest departure time is %s, arriving at %s.\n\n",
result->departure, result->arriving);
system("pause");
return 0;
}