C语言根据日期判断星期几,使用基姆拉尔森计算公式:
W= (d+2*m+3*(m+1)/5+y+y/4-y/100+y/400) mod 7
在公式中d表示日期中的日数,m表示月份数,y表示年数。
注意:
把一月和二月看成是上一年的十三月和十四月,例:如果是2004-1-10则换算成:2003-13-10来代入公式计算。
以公元元年为参考,公元元年1月1日为星期一
参考代码:
#include
void CaculateWeekDay(int y,int m, int d)
{
if(m<=2) {
m+=12;
y--;
}
int iWeek=(d+2*m+3*(m+1)/5+y+y/4-y/100+y/400)%7;
switch(iWeek)
{
case 0: printf("星期一\n"); break;
case 1: printf("星期二\n"); break;
case 2: printf("星期三\n"); break;
case 3: printf("星期四\n"); break;
case 4: printf("星期五\n"); break;
case 5: printf("星期六\n"); break;
case 6: printf("星期日\n"); break;
}
}
void main()
{
CaculateWeekDay(2015,10,1);
}
//#include "stdafx.h"//If the vc++6.0, with this line.
#include "stdio.h"
int main(void){
int y,g;
char *w[7]={"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"};
char s[4]={0,5,3,1};//需要用这个表协助一下
while(1){
printf("Input year...\ny=");
if(scanf("%d",&y) && y>0)
break;
printf("Error, Year must be greater than 0: ");
}
g=((y%100+y%100/4)%7+s[y/100%4]-(y%4==0 && y%100!=0 || y%400==0))%7;//这就是公式
printf("%d-1-1 is %s\n",y,w[g]);
return 0;
}
#include "stdio.h"
void CaculateWeekDay(int y,int m, int d)
{
if(m==1||m==2) {
m+=12;
y--;
}
int iWeek=(d+2*m+3*(m+1)/5+y+y/4-y/100+y/400)%7;
switch(iWeek)
{
case 0: printf("星期一\n"); break;
case 1: printf("星期二\n"); break;
case 2: printf("星期三\n"); break;
case 3: printf("星期四\n"); break;
case 4: printf("星期五\n"); break;
case 5: printf("星期六\n"); break;
case 6: printf("星期日\n"); break;
}
}
int main()
{
int year=0,month=0,day=0;
printf("请输入日期:\n格式为:1900,1,1\n");
char temp = '1';
while (temp != '0')
{
scanf("%d,%d,%d",&year,&month,&day);
scanf("%c",&temp);
CaculateWeekDay(year,month,day);
printf("输入0退出,其他继续:");
scanf("%c",&temp);
}
}
/*打印任意年份的月历*/
/*****Calendar.c*****/
#include
#include
int week(int year,int month); //函数原型 该函数用以返回某年某月1号的星期及
int days(int year,int month); //该函数用来返回该月的天数
int main(void)
{
int y,m;
int da,we;
printf("Please enter Year and Month:[1900.1.1--]\n"); //1900.1.1为星期一,以此为初始
scanf("%d%d",&y,&m);
da=days(y,m);
we=week(y,m);
//printf("%d\n\n",we);
printf("Sun\tMon\tTue\tWed\tThu\tFri\tSat\n");
int i; int day[40];
int k=1;
for(i=0;i
i=0;
for(;i<(da+we);)
{
for(k=1;k<=7;k++)
{
if(day[i]==0)printf(" \t");
else printf("%3d\t",day[i]);
i++;
if (i>=da+we)break;
}
printf("\n");
}
printf("\n");
system("PAUSE");
return 0;
}
//返回星期函数
int week(int year,int month)
{
int sum=0,i,count=0;
for(i=1900;i
}
//返回天数函数
int days(int year,int month)
{
int m[]={31,28,31,30,31,30,31,31,30,31,30,31};
//判断是否闰年
if((year%4==0&&year%100!=0)||year%400==0)m[1]=29;
return(m[month-1]);
}