C语言编程求日期
发布网友
发布时间:2022-04-21 14:14
我来回答
共1个回答
热心网友
时间:2023-09-29 09:42
YMD_2_JD() 计算年月日 是 该年的第几天。
YMD_2_WeekDay()计算某年月日 是 星期几,用 WeekDayName[] 显示星期几的字符串。
#include<stdio.h>
int YMD_2_JD(int Y, int M, int D){
const short MonthDay[]={0,31,28,31,30,31,30,31,31,30,31,30,31};
int JD,i;
JD=D;
for (i=0;i<M;i++) JD+=MonthDay[i];
if (((Y%4==0)&&(Y%100!=0)||(Y%400==0)) && (M>2)) JD++;
return JD;
}
int YMD_2_WeekDay(int Y, int M, int D){
int offset,jd,weekD;
offset = ((Y-1)+(Y-1)/4-(Y-1)/100+(Y-1)/400) % 7 ;
jd = YMD_2_JD(Y,M,D);
weekD = (jd + offset) % 7;
return weekD;
}
char *WeekDayName[]={" ","Mon","Tue","Wen","Thu","Fri","Sat","Sun"};
main(){
int Y,M,D;
printf("input year month day, for example 2015 3 31:\n");
scanf("%d %d %d",&Y,&M,&D);
printf("It is %dth day\n",YMD_2_JD(Y,M,D));
printf("It is %s.\n",WeekDayName[YMD_2_WeekDay(Y,M,D)]);
return 0;
}追问你运行过了吗~可以区分闰年平年的不同吗
追答程序考虑了 闰年平年:
if (((Y%4==0)&&(Y%100!=0)||(Y%400==0)) && (M>2)) JD++;
-----------
星期几的字符串数组里的第一个漏写 Sunday, 你要用,可以加上.
char *WeekDayName[]={"Sun","Mon","Tue","Wen","Thu","Fri","Sat","Sun"};