编写一个程序,只要输入年月日,就能回答那天是星期几。
输入一个日期,包括年、月、日。(一组测试数据)
输出这个日期是星期几。
输入:
1 1 1
2 1 1
2006 7 10
输出:
Monday
Tuesday
Monday
代码:
//==================================================== //名称:计算生日是星期几(0078) //作者:郭成涛 //时间:2015-11-22 //简介:编写一个程序,只要输入年月日,就能回答那天是星期几。 //==================================================== #include<stdio.h> int main() { int mon[12]={31,28,31,30,31,30,31,31,30,31,30,31}; int y,m,d,i,sum=0,j=0; scanf("%d%d%d",&y,&m,&d); for(i=1;i<y;i++)//从1年到当前年,计算总天数 { sum=sum+365; if((i%4==0&&i%100!=0)||i%400==0) { sum++; } } for(i=0;i<m-1;i++)//后面还要加天数,所以少算一个月 { sum=sum+mon[i]; if(m>1&&(y%4==0&&y%100!=0)||y%400==0) sum++; } sum=sum+d; //计算天 j=sum%7; switch(j) { case 0:printf("Sunday ");break; case 1:printf("Monday ");break; case 2:printf("Tuesday ");break; case 3:printf("Wednesday ");break; case 4:printf("Thursday ");break; case 5: printf("Friday ");break; case 6: printf("Saturday ");break; } return 0; }
换一种方式:
#include <stdio.h> int main() { int y, m, d, i; int year, day; int month[] = {0, 31, 0, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; char week[][10] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; while (scanf("%d %d %d", &y, &m, &d) == 3){ year = 1; day = d; while (year < y){ day += year%400==0||(year%4==0&&year%100!=0) ? 366 : 365; year++; } if (y%400==0||(y%4==0&&y%100!=0)) month[2] = 29; else month[2] = 28; for (i=1; i<m; i++) day += month[i]; printf("%s ", week[day%7]); } return 0; }