[置顶] C语言实验:输入任意一个日期的年、月、日的值,求出从公元1年1月1日到这一天总共有多少天,并求出这一天是星期几。
要求:输入任意一个日期的年、月、日的值,求出从公元1年1月1日到这一天总共有多少天,并求出这一天是星期几。
简单的循环结构,并结合基姆拉尔森公式,注意月份转换。
下面是源码,仅供参考:
#include <iostream> using namespace std; void month1(int i, int count) { switch (i) { case 1:count += 31;break; case 2:count += 29;break; case 3:count += 31;break; case 4:count += 30;break; case 5:count += 31;break; case 6:count += 30;break; case 7:count += 31;break; case 8:count += 31;break; case 9:count += 30;break; case 10:count += 31;break; case 11:count += 30;break; case 12:count += 31;break; } } void month2(int &i, int &count) { switch (i) { case 1:count += 31;break; case 2:count += 29;break; case 3:count += 31;break; case 4:count += 30;break; case 5:count += 31;break; case 6:count += 30;break; case 7:count += 31;break; case 8:count += 31;break; case 9:count += 30;break; case 10:count += 31;break; case 11:count += 30;break; case 12:count += 31;break; } } void day1(int a) { switch(a) { case 1: cout<<"Monday"<<endl;break; case 2: cout<<"Tuesday"<<endl;break; case 3: cout<<"Wednesday"<<endl;break; case 4: cout<<"Thursday"<<endl;break; case 5: cout<<"Friday"<<endl;break; case 6: cout<<"Saturday"<<endl;break; case 7: cout<<"Sunday"<<endl;break; } } int main() { int year, month, day; while(1) { int count = 0; cout<<"Please input the date as the following format\nyear-month-day\n\n"; cin>>year>>month>>day; for(int i = 1; i < year; i ++) { if((i % 4 == 0 && i % 100 != 0)||(i % 400 == 0)) { count += 366; } else { count += 365; } } for(int i = 1; i < month; i++) { if((year % 4 == 0 && year % 100 != 0)||(year % 400 == 0)) { month1(i,count); } else { month2(i,count); } } count += day; cout<<endl<<"Days between 1-1-1 and "<<year<<'-'<<month<<'-'<<day<<" is(are) "<<count<<" day(s)"<<endl<<endl; if(month==1||month==2) { month+=12; year--; } int d = (2+2*month+3*(month+1)/5+year+year/4-year/100+year/400)%7; if(d==0) { d=7; } cout<<"That day is "; day1(d); cout<<endl; } }