主题:[原创]【回顾】C语言日期的编写
题目:日期的处理及应用
需求定义:
完成一个在控制台打印要查询日期的日历格式。如:控制台输入2009 01则打印出日历如下
编写程序实现让用户输入日期,如果输入的日期只有年和月的话列出某年某月的日历,如果输入的日期有年月日的话,列出某年某月某日是星期几,这月总共有多少天,今年是闰年还是平年
代码编写:
#include <stdio.h>
//判断是否是闰年
int isLeap(int year)
{
if((year % 4 == 0) && (year % 100 != 0)||(year % 400 == 0))
return 1;
else
return 0;
}
//计算一个月有多少天
int daysOfMonth(int year,int month)
{
int days = 31;
if(month == 4 || month == 6 || month == 9 || month == 11)
days = 30;
if(month == 2)
days = (isLeap(year)?29:28);
return days;
}
//计算从公元元年到今天共有多少天
int totalDays(int year,int month,int day)
{
int sum = 0;
int i,j;
for(i=1;i<year;i++)
{
sum += 365+isLeap(i);
}
for(i=1;i<month;i++)
{
sum += daysOfMonth(year,i);
}
sum += day;
return sum;
}
int main(void)
{
int year,month,day;
int sum;
int weekday;
int i;
do
{
printf("please enter the date(yyyy-mm-dd)\n");
scanf("%d-%d-%d",&year,&month,&day);
}while(year<1600 || month<1 || month>12 || day<1 || day>daysOfMonth(year,month));
sum = totalDays(year,month,day);
weekday = sum % 7;
printf("the day is 星期%d\n",weekday);
printf(" su mo tu we th fr sa \n");
weekday = totalDays(year,month,1)%7;
printf("%*s",weekday*3," ");
sum = daysOfMonth(year,month);
for(i=1;i<=sum;i++)
{
printf("%3d",i);
if(++weekday%7==0)
printf("\n");
}
printf("\n");
}
欢迎交流![url=http://www.bsechr.com.cn/news.asp?anclassid=58&mnclassid=165]嵌入式知识专栏[/url]
需求定义:
完成一个在控制台打印要查询日期的日历格式。如:控制台输入2009 01则打印出日历如下
编写程序实现让用户输入日期,如果输入的日期只有年和月的话列出某年某月的日历,如果输入的日期有年月日的话,列出某年某月某日是星期几,这月总共有多少天,今年是闰年还是平年
代码编写:
#include <stdio.h>
//判断是否是闰年
int isLeap(int year)
{
if((year % 4 == 0) && (year % 100 != 0)||(year % 400 == 0))
return 1;
else
return 0;
}
//计算一个月有多少天
int daysOfMonth(int year,int month)
{
int days = 31;
if(month == 4 || month == 6 || month == 9 || month == 11)
days = 30;
if(month == 2)
days = (isLeap(year)?29:28);
return days;
}
//计算从公元元年到今天共有多少天
int totalDays(int year,int month,int day)
{
int sum = 0;
int i,j;
for(i=1;i<year;i++)
{
sum += 365+isLeap(i);
}
for(i=1;i<month;i++)
{
sum += daysOfMonth(year,i);
}
sum += day;
return sum;
}
int main(void)
{
int year,month,day;
int sum;
int weekday;
int i;
do
{
printf("please enter the date(yyyy-mm-dd)\n");
scanf("%d-%d-%d",&year,&month,&day);
}while(year<1600 || month<1 || month>12 || day<1 || day>daysOfMonth(year,month));
sum = totalDays(year,month,day);
weekday = sum % 7;
printf("the day is 星期%d\n",weekday);
printf(" su mo tu we th fr sa \n");
weekday = totalDays(year,month,1)%7;
printf("%*s",weekday*3," ");
sum = daysOfMonth(year,month);
for(i=1;i<=sum;i++)
{
printf("%3d",i);
if(++weekday%7==0)
printf("\n");
}
printf("\n");
}
欢迎交流![url=http://www.bsechr.com.cn/news.asp?anclassid=58&mnclassid=165]嵌入式知识专栏[/url]