回复 9楼 lonmaor
同样n1,n2,n3一个用于判断当日time距sleep_time的间隔,一个用于判断下一日time距sleep_time的间隔,一个用于判断前一日time距sleep_time的间隔。
程序代码:
#include <stdio.h>
#include <stdlib.h>
#define TIME_TAB_MAX 10
char g_tab_time[TIME_TAB_MAX][6] =
{
"22:08",
"08:31",
"18:25",
"21:35",
"01:35",
"23:59",
"01:03",
"09:34",
"07:23",
"09:59"
};
char g_sleep_time[6] = {
"00:03"
};
int timeToMinute(char* myTime)
{
return (myTime[0]*10 + myTime[1]) * 60 + (myTime[3]*10 + myTime[4]);
}
char* nearestTime(char sleep_time[], char tab_time[][6], int TAB_MAX)
{
int sleep_minute = timeToMinute(sleep_time);
int* tab_minute = (int*) malloc(sizeof(int) * TAB_MAX);
int i,t,n1,n2,n3;
int min = 24*60*2;
for(i=0; i!=TAB_MAX; i++)
{
tab_minute[i] = timeToMinute(tab_time[i]);
n1 = 24*60 + tab_minute[i] - sleep_minute;
n2 = tab_minute[i] - sleep_minute;
n2 = n2>0 ? n2: (-1)*n2;
n3 = 24*60 + sleep_minute - tab_minute[i];
if(n1 < min)
{
min = n1;
t = i;
}
if (n2 < min)
{
min = n2;
t = i;
}
if (n3 < min)
{
min = n3;
t = i;
}
}
free(tab_minute);
return tab_time[t];
}
int main()
{
printf("%s",nearestTime(g_sleep_time,g_tab_time,TIME_TAB_MAX));
return 0;
}
[
本帖最后由 lonmaor 于 2012-6-15 10:49 编辑 ]