給定一個天數,計算該天在某年的月、日

#include <stdio.h>

void getMonthAndDays(int year, int *month, int *day);

int main()
{
int month = 0;
int day = 63;
getMonthAndDays(2012, &month, &day);
printf("month:%2d day: %2d", month, day);
return 0;
}

void getMonthAndDays(int year, int *month, int *day)
{
if (year > 0 && (*day) > 0)
{
int y = (year%100 != 0 && year%4 == 0) || (year%400 == 0); //閏年
int days[] = {31, 28 + y, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; //初始化一個數組,記錄每月的天數 
// days[1] += (year%100 != 0 && year%4 == 0) || (year%400 == 0); //閏年,二月多一天 
for (*month = 1; *day - days[*month - 1] > 0; (*month)++) //若是day的值比下一個月的天數多,則減去,月數加1 
{
*day -= days[*month - 1];
}
}
}
相關文章
相關標籤/搜索