标签:
#include <stdio.h> #include <stdlib.h> /* 输入一个日期,输出该日期是星期几。 */ int monthDays[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; int getWeekDay(int year, int month, int day); int isGoodYear(int year); int isGoodMonth(int month); int isGoodDay(int year, int month, int day); int isLeapYear(int year); int dayOfYear(int year, int month, int day); int daysBetweenYear(int year1, int year2); int daysBetweenDays(int year1, int month1, int day1, int year2, int month2, int day2); int main(){ int year, month, day; while (fflush(stdin), scanf("%d%d%d", &year, &month, &day) != EOF){ if (isGoodYear(year) && isGoodMonth(month) && isGoodDay(year, month, day)) //判断输入是否合法 printf("%d\n", getWeekDay(year,month,day)); else printf("Please input a right date.\n"); } system("pause"); return 0; } int getWeekDay(int year, int month, int day){ //基准取2016/1/3,周日 //SUN返回0 //MON-SAT分别返回1-6 if ((year >= 2016) && (month >= 1) && (day >= 3)) return daysBetweenDays(2016, 1, 3, year, month, day) % 7; else return (7 - daysBetweenDays(year, month, day, 2016, 1, 3) % 7) % 7; } int daysBetweenDays(int year1, int month1, int day1, int year2, int month2, int day2){ //日期1<日期二为负数 //日期1>日期二为正数 int days1 = dayOfYear(year1, month1, day1); int days2 = dayOfYear(year2, month2, day2); int days3 = daysBetweenYear(year1, year2); int totalDays = days2 + days3 - days1; return totalDays; } int daysBetweenYear(int year1, int year2){ //year1 < year2为正数 //year1 > year2为负数 int maxYear = (year1 > year2) ? year1 : year2; int minYear = (year1 > year2) ? year2 : year1; int totalDays = 0; for (int i = minYear; i < maxYear; ++i) if (isLeapYear(i)) totalDays += 366; else totalDays += 365; if (minYear == year1) return totalDays; else return -totalDays; } int dayOfYear(int year, int month, int day){//当年第几天 int total = 0; for (int i = 0; i < month - 1; ++i) total += monthDays[i]; total += day; if (isLeapYear(year) && (month > 2)) total++; return total; } int isLeapYear(int year){ if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) return 1; else return 0; } int isGoodYear(int year){ if (year >= 1900) return 1; else return 0; } int isGoodMonth(int month){ if ((month >= 1) && (month <= 12)) return 1; else return 0; } int isGoodDay(int year, int month, int day){ switch (month) { case 2: if (isLeapYear(year)) if ((day >= 1) && (day <= 29)) return 1; else if ((day >= 1) && (day <= 28)) return 1; else return 0; case 4: case 6: case 9: case 11: if ((day >= 1) && (day <= 30)) return 1; else return 0; case 1: case 3: case 5: case 7: case 8: case 10: case 12: if ((day >= 1) && (day <= 31)) return 1; else return 0; default: printf("month error in day judge.\n"); return 0; } }
标签:
原文地址:http://www.cnblogs.com/mutaohengheng/p/5104957.html