假定输入日期合法正确。
先找一个参考日期,找星期天的日期为最好。我一时没想到就选了今天,星期一,也不错。然后求出输入日期与参考日期之间间隔的天数n,n为负时则表示输入日期在参考日期之前,n为正时则表示输入日期在参考日期之后。因为星期为循环星期1到星期天,又根据补码的原理,可知n = ((n % 7) + 8) % 7, 此时的n为几则是星期几。(PS:星期天用0来表示,因为我选的是参考日期是星期一所以是+8,如果选的是星期天则是+7)。
1 //给定一个日期,求这个日期是星期几? 2 #include <stdio.h> 3 #include <stdlib.h> 4 5 int is_leap_year(unsigned y); 6 unsigned days_in_year(unsigned y, unsigned m, unsigned d); 7 void swap(unsigned *m, unsigned *n); 8 int days(unsigned y1, unsigned m1, unsigned d1); 9 10 int main(int argc, char *argv[]) 11 { 12 unsigned y, m, d; 13 int n, res; 14 15 while (fflush(stdin),(res = scanf("%d%d%d", &y, &m, &d)) != EOF) 16 { 17 n = days(y, m, d); 18 n %= 7; 19 n = (n + 8) % 7 ; 20 printf("%d年%d月%d日是星期%d\n", y, m, d, n); 21 } 22 system("pause"); 23 return 0; 24 } 25 26 int is_leap_year(unsigned y) 27 { 28 if((y % 4 == 0 && y % 100 != 0) || y % 400 == 0) 29 return 1; 30 else 31 return 0; 32 } 33 34 unsigned days_in_year(unsigned y, unsigned m, unsigned d) 35 { 36 unsigned n = 0, i; 37 unsigned months[13] = {0,31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; 38 39 if(is_leap_year(y)) 40 months[2] = 29; 41 else 42 months[2] = 28; 43 for ( i = 1; i < m; i++) 44 n += months[i]; 45 n += d; 46 return n; 47 } 48 49 void swap(unsigned *m, unsigned *n) 50 { 51 unsigned tmp; 52 tmp = *m; 53 *m = *n; 54 *n = tmp; 55 } 56 57 int days(unsigned y2, unsigned m2, unsigned d2) 58 { 59 unsigned y1, m1, d1, i, n = 0; 60 int flag = 0; 61 62 y1 = 2015; 63 m1 = 3; 64 d1 = 9; 65 if ( y1 > y2 || (y1 == y2 && m1 > m2) || (y1 == y2 && m1 == m2 && d1 > d2)) 66 { 67 flag = 1; 68 swap(&y1, &y2); 69 swap(&m1, &m2); 70 swap(&d1, &d2); 71 } 72 if (y1 != y2) 73 { 74 if (is_leap_year(y1)) 75 n += 366 - days_in_year(y1, m1, d1); 76 else 77 n += 365 - days_in_year(y1, m1, d1); 78 for ( i = y1 + 1; i < y2; i++) 79 { 80 if( is_leap_year(i) ) 81 n += 366; 82 else 83 n += 365; 84 } 85 n += days_in_year(y2, m2, d2); 86 } 87 else 88 n = days_in_year(y2, m2, d2) - days_in_year(y1, m1, d1); 89 if (flag) n = -n; 90 return n; 91 }
时间: 2024-10-23 02:27:20