如何让编写一个显示时间的小程序 用C或C++

就像一个小钟表之类的 希望给个代码 谢谢啊
2024-12-25 07:08:22
推荐回答(1个)
回答1:

//其实这个并不难,只要你学习一下time.h中的时间函数就能自己做了。
#include
#include
#include
#include
typedef struct
{
int year;
int month;
int day;
int hour;
int minute;
int second;
int week;
}myDate;
int leap(int year)
{
if (year%4 == 0 && year%100 !=0 || year%400 == 0)
{
return 1;
}
return 0;
}

int main()
{
int days[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
char * weekday[] = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
time_t t = time(NULL);
struct tm *cur = localtime(&t);
myDate Date = {cur->tm_year+1900, cur->tm_mon + 1, cur->tm_mday, cur->tm_hour, cur->tm_min, cur->tm_sec, cur->tm_wday};

printf("%4d年%02d月%02d日[%s]%02d时%02d分%02d秒\r", Date.year, Date.month, Date.day, weekday[Date.week], Date.hour, Date.minute, Date.second);
while(1)
{
Sleep(1000);
days[2] = (leap(Date.year) ? 28:29);
Date.second++;
if ( Date.second == 60)
{
Date.second = 0;
Date.minute++;
}

if (Date.minute == 60)
{
Date.minute = 0;
Date.hour++;
}

if (Date.hour == 24)
{
Date.hour = 0;
Date.week = (++Date.week)%7;
Date.day++;
}

if (Date.day == (days[Date.month] + 1))
{
Date.day = 1;
Date.month++;
}

if (Date.month == 13)
{
Date.month = 1;
Date.year++;
}

printf("%4d年%02d月%02d日[%s]%02d时%02d分%02d秒\r", Date.year, Date.month, Date.day, weekday[Date.week], Date.hour, Date.minute, Date.second);
//时间的不换行显示是通过'\r'来实现的
}

return 0;
}