抱歉,我的代码现在可以编译,但是每次运行时,它都会返回小时,分钟,天和月的随机值。
下面的我的函数始终以格式返回随机值每次运行程序时,HOUR:MIN:DAY:MONTH,我不确定为什么它会一直返回随机数。我已经坚持了一段时间,任何人都可以看到我做错了什么,为什么?
谢谢!
int main(void)
{
int hours,minutes,day,month;
time_t now;
struct tm *tm = localtime(&now);
char buffer[100];
int a = tm->tm_hour, b=tm->tm_min, c=tm->tm_mday, d=tm->tm_mon;
sprintf(buffer,"02%d02%d02%d02%d",a,b,c,d);
hours = tm->tm_hour;
minutes = tm->tm_min;
day = tm->tm_mday;
month = tm->tm_mon + 1;
if (hours < 24)
{
printf("Time is : %02d:%02d:%02d:%02d\n", hours, minutes, day,month);
}
else
{
printf("Time is : %02d:%02d:%02d:%02d\n", hours - 12, minutes, day,month);
}
return 0;
}
下面的代码是我用作参考的。
int main(void)
{
int hours, minutes, seconds, day, month, year;
// time_t is arithmetic time type
time_t now;
// Obtain current time
// time() returns the current time of the system as a time_t value
time(&now);
// Convert to local time format and print to stdout
printf("Today is : %s", ctime(&now));
// localtime converts a time_t value to calendar time and
// returns a pointer to a tm structure with its members
// filled with the corresponding values
struct tm *local = localtime(&now);
hours = local->tm_hour; // get hours since midnight (0-23)
minutes = local->tm_min; // get minutes passed after the hour (0-59)
seconds = local->tm_sec; // get seconds passed after minute (0-59)
day = local->tm_mday; // get day of month (1 to 31)
month = local->tm_mon + 1; // get month of year (0 to 11)
year = local->tm_year + 1900; // get year since 1900
// print local time
if (hours < 12) // before midday
printf("Time is : %02d:%02d:%02d am\n", hours, minutes, seconds);
else // after midday
printf("Time is : %02d:%02d:%02d pm\n", hours - 12, minutes, seconds);
// print current date
printf("Date is : %02d/%02d/%d\n", day, month, year);
return 0;
}
sprintf(buffer,"%02d%02d%02d%02d",a,b,c,d);
%
需要放在宽度说明符之前。