万年历的C语言实现

// Zeller公式确定星期几,w=y+[y/4]+[c/4]-2c+[26(m+1)/10]+d-1

// y是年份取最后两位,c是世纪减1,m是月份,如果m是1月和2月,则m换成13和14,d是日期,[]表示取整,w除以7之后的余数就是星期几,如果余数为0,就是星期日


#include <stdio.h>


int main()

{

int year, month, y;

printf("请输入年:\n");

scanf("%d", &year);

if (year < 1900)

{

printf("年必须大于1900\n");

exit(-1);

}

y = year;

int c = y;

y %= 100;

c /= 100;

int m;

printf("请输入月:\n");

scanf("%d", &month);

if ((month < 0) || (month > 12))

{

printf("月在1--12之间\n");

exit(-1);

}

m = month;

if (1 == m)

{

m = 13;

}

if (2 == m)

{

m = 14;

}

int d;

printf("请输入日期:\n");

scanf("%d", &d);

if ((d < 0) || (d > 31))

{

printf("日期必须在1和31之间\n");

exit(-1);

}

int w =

y + (int)y / 4 + (int)c / 4 - 2 * c + (int)(26 * (m + 1) / 10) + d - 1;

w %= 7;

char r[20];

switch (w)

{

case 0:

sprintf(r,"%s","星期天");

break;

case 1:

sprintf(r,"%s","星期一");

break;

case 2:

sprintf(r,"%s","星期二");

break;

case 3:

sprintf(r,"%s","星期三");

break;

case 4:

sprintf(r,"%s","星期四");

break;

case 5:

sprintf(r,"%s","星期五");

break;

case 6:

sprintf(r,"%s","星期六");

break;

default:

exit(-1);

}

printf("\n%d-%d-%d:%s\n", year, month, d, r);

return 0;

}


你可能感兴趣的:(万年历,C程序)