/*
1.定义一个结构体变量(包括年、月、日),计算该日在本年中为第几天?(注意考虑闰年问题),要求写一个函数days,实现上面的计算。由主函数将年月日传递给days函数,计算后将日子传递回主函数输出。
*/
typedef struct date{ int year; int month; int day; }Date;
BOOL isLeapYear(int year);//判断是否是闰年 BOOL isLeapYear(int year) { if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0){ return YES; } return NO; }
int days(Date someDate);//计算天数 int days(Date someDate) { int totalDaysFromYearStart = 0; switch (someDate.month) { case 12: totalDaysFromYearStart += 30; case 11: totalDaysFromYearStart += 31; case 10: totalDaysFromYearStart += 30; case 9: totalDaysFromYearStart += 31; case 8: totalDaysFromYearStart += 31; case 7: totalDaysFromYearStart += 30; case 6: totalDaysFromYearStart += 31; case 5: totalDaysFromYearStart += 30; case 4: totalDaysFromYearStart += 31; case 3: totalDaysFromYearStart += 28; totalDaysFromYearStart += isLeapYear(someDate.year) ? 1 : 0; case 2: totalDaysFromYearStart += 31; case 1: default: break; } totalDaysFromYearStart += someDate.day; return totalDaysFromYearStart; }
|