法一:
#include <stdio.h>
#include <stdlib.h>
int LeapYear(int year);
void MonthDay(int year, int yearDay , int *pMonth , int *pDay);
#define MONTHS 12
int main()
{
int year,yearDay,*pMonth=NULL ,*pDay = NULL;
do{
printf("please input year and days: ");
scanf("%d%d",&year,&yearDay);
}while(yearDay < 0 || yearDay > 366);
MonthDay(year, yearDay , &pMonth , &pDay);
return 0;
}
int LeapYear(int year)
{
int flag = 0 ;
if((year % 4 == 0 && year % 100 != 0) || ( year % 400 == 0))
flag = 1;
else
flag = 0;
return flag;
}
void MonthDay(int year, int yearDay , int *pMonth , int *pDay)
{
int i ,count = 1;
int Days[2][MONTHS] = {
{31,29,31,30,31,30,31,31,30,31,30,31},
{31,28,31,30,31,30,31,31,30,31,30,31}
};
if(LeapYear(year))
{
if(yearDay <= 31)
{
*pMonth = 1;
*pDay = yearDay;
}
else
{
for(i = 0 ; yearDay > 0; i++)
{
yearDay -= Days[0][i];
count ++;
if(yearDay > Days[0][i+1])
continue;
else break;
}
*pMonth = count ;
*pDay = yearDay;
}
printf("the month is %d ,the day is %d\n",*pMonth,*pDay);
}
else
{
if(yearDay <= 31)
{
*pMonth = 1;
*pDay = yearDay;
}
else
{
for(i = 0 ; yearDay > 0; i++)
{
yearDay -= Days[1][i];
count ++;
if(yearDay > Days[1][i+1])
continue;
else break;
}
*pMonth = count ;
*pDay = yearDay;
}
printf("the month is %d ,the day is %d\n",*pMonth,*pDay);
}
}
法二 (精简版)
#include <stdio.h>
#include <stdlib.h>
int LeapYear(int year);
void MonthDay(int year, int yearDay , int *pMonth , int *pDay);
#define MONTHS 12
int main()
{
int year,yearDay,Month=0 ,Day = 0;
do{
printf("please input year and days: ");
scanf("%d%d",&year,&yearDay);
}while(yearDay < 0 || yearDay > 366);
MonthDay(year, yearDay , &Month , &Day);
return 0;
}
int LeapYear(int year)
{
int flag = 0 ;
if((year % 4 == 0 && year % 100 != 0) || ( year % 400 == 0))
flag = 1;
else
flag = 0;
return flag;
}
void MonthDay(int year, int yearDay , int *pMonth , int *pDay)
{
int i,flag=0 ;
int Days[2][MONTHS] = {
{31,28,31,30,31,30,31,31,30,31,30,31},
{31,29,31,30,31,30,31,31,30,31,30,31}
};
flag = LeapYear(year);
for(i = 0; i < MONTHS; i++)
{
if(yearDay>Days[flag][i])
yearDay -= Days[flag][i];
else
{
*pMonth = i+1;
*pDay = yearDay;
printf("the month is %d ,the day is %d\n",*pMonth,*pDay);
break;
}
}
}