输入年月日,计算这是一年中的第几天以及计算这天是星期几

tech2022-07-10  177

先来看如何计算这是一年中的第几天:

#include <stdio.h> int main() { int year,month,day,sum=0; scanf("%d%d%d",&year,&month,&day); for(int i=1;i<month;i++) //计算月份总和起来的天数 { if(i==1||i==3||i==5||i==7||i==8||i==10) sum+=31; else if(i==2) { if((year%4==0&&year%100!=0)||year%400==0) sum+=29; //注意闰年 else sum+=28; } else sum+=30; } sum+=day; //加上除开月份的天数 printf("%d",sum); }

接下来看如何求星期几:

#include <stdio.h> int Getweekday(int year,int month,int day) { int sum=0; for(int i=1;i<year;i++) //计算年份所包含的天数 { if((i%4==0&&i%100!=0)||i%400==0) sum+=366; else sum+=365; } for(int i=1;i<month;i++) //计算月份所包含的天数 { if(i==1||i==3||i==5||i==7||i==8||i==10) sum+=31; else if(i==2) { if((year%4==0&&year%100!=0)||year%400==0) sum+=29; else sum+=28; } else sum+=30; } sum+=day; //加上原有的天数 return sum%7; } int main() { int year,month,day; scanf("%d%d%d",&year,&month,&day); while(year!=0&&month!=0&&day!=0) { int a=Getweekday(year,month,day); switch(a){ case 1: printf("%s\n","Monday"); break; case 2: printf("%s\n","Tuseday"); break; case 3: printf("%s\n","Wednesday"); break; case 4: printf("%s\n","Thursday"); break; case 5: printf("%s\n","Friday"); break; case 6: printf("%s\n","Saturday"); break; case 0: printf("%s\n","Sunday"); break; } scanf("%d%d%d",&year,&month,&day); } }

最新回复(0)