本人C语言小萌新,现在才学到函数,以下是今天写的日历的代码,让大佬们见笑了。
这是想象中代码实现的。
#include <stdio.h>
//函数1闰年平年的判断
int isrun(int year)
{
if(year%4==0&&year%100!=0||year%400==0)
{
return 1;
}
else
{
return 0;
}
}
//函数2计算某年某月有多少天
int isnum(int year,int month)
{
int res;
res=isrun(year);
if(month==2)
{
if(res==1)
//if(year%4==0&&year%100!=0||year%400==0)
{
//年份是闰年
return 29;
}
else
{
//年份是平年
return 28;
}
}
else if(month==1||month==3||month==5||month==7||month==8||month==10||month==12){
return 31;
}
else {
return 30;
}
}
//函数3求输入的某年某月1日与 1970年1月1日天数之差
int isday(int year,int month)
{
int chu,res,initial;
int day=0;
for(chu=1970;chu<year;chu++){
res=isrun(chu);
if(res==1)
{
day=day+366;
}
else
{
day=day+365;
}
}
for(initial=1;initial<month;initial++){
res=isnum(year,initial);
day=day+res;
}
return day;
}
//求某年某月1日是星期几
int isweek(int year,int month)
{
int res,week;
res=isday(year,month);
week=res%7;
if(week<=3)
{
week=week+4;
}
else
{
week=week-3;
}
return week;
}
int main(void)
{
int year1,year2,month1,month2,date1,date2,date3;
int i,j,res;
int z=0;
printf("请输入要打印的年份和月份:");
scanf("%d %d",&year1,&month1);
res=isweek(year1,month1);
if(month1==1)
{
year2=year1-1;
month2=12;
}
else
{
year2=year1;
month2=month1-1;
}
//上个月的天数
date2=isnum(year2,month2);
//本月的天数
date1=isnum(year1,month1);
//下个月的天数
date3=42-(res-1)-date1;
j=date2-(res-1)+1;
printf("%d年%d月\n",year1,month1);
printf(" 周一 周二 周三 周四 周五 周六 周日 \n");
for(i=1;i<res;i++)
{
z++;
printf(" %3d ",j++);
}
for(i=1;i<=date1;i++)
{
z++;
if(z%7==0)
{
printf(" %3d\n",i);
}
else
{
printf(" %3d ",i);
}
}
for(i=1;i<=date3;i++)
{
z++;
if(z%7==0)
{
printf(" %3d\n",i);
}
else
{
printf(" %3d ",i);
}
}
return 0;
}
最后运行代码后的样子,还是有差别的