课程首页在:http://blog.csdn.net/sxhelijian/article/details/11890759
【项目1-当年第几天】
定义一个函数,其参数为年、月、日的值,返回这一天为该年的第几天。要求在main函数中输入年月日,然后调用这个函数求值,并在main函数中输出结果。
参考解答1:
#include<iostream> using namespace std; int days(int y, int m, int d); int main() { int year, month, day; cout<<"输入年 月 日"<<endl; cin>>year>>month>>day; cout<<"这是该年的第"<<days(year, month, day)<<"天"<<endl; return 0; } int days(int y, int m, int d) { int sum=d; //加上前m-1月的天数 for(int i=1;i<m;i++) { switch(i) { case 2: sum+=((y%4==0&&y%100!=0)||y%400==0)?29:28; break; case 4: case 6: case 9: case 11: sum+=30; break; default: sum+=31; break; } } return sum; }
用类似思路,有参考解答2:
#include<iostream> using namespace std; int days(int y, int m, int d); int main() { int year, month, day; cout<<"输入年 月 日"<<endl; cin>>year>>month>>day; cout<<"这是该年的第"<<days(year, month, day)<<"天"<<endl; return 0; } int days(int y, int m, int d) { int sum=d; //加上前m-1月的天数 for(int i=1; i<m; i++) { if(i==1||i==3||i==5||i==7||i==8||i==10||i==12) sum+=31; else if (i==4||i==6||i==9||i==11) sum+=30; else sum+=((y%4==0&&y%100!=0)||y%400==0)?29:28; } return sum; }
下下周学习了数组,可以这样来,30行之内解决问题(对数组充满期待吧):
#include<iostream> using namespace std; int days(int y, int m, int d); int main() { int year, month, day; cout<<"输入年 月 日"<<endl; cin>>year>>month>>day; cout<<"这是该年的第"<<days(year, month, day)<<"天"<<endl; return 0; } int days(int y, int m, int d) { int sum=d; int a[13]= {0,31,28,31,30,31,30,31,31,30,31,30,31}; for(int i=1; i<m; i++) { sum+=a[i]; } if(m>2&&((y%4==0&&y%100!=0)||y%400==0)) //若闰年,且晚于2月,加一天 sum++; return sum; }
有同学写成下面的代码,结果对,但这样的程序的确不好:
#include <iostream> using namespace std; int shijian(int year,int month,int day); int main() { int year,month,day,t; cout<<"要知道今天是今年第几天吗?请输入年月日:"<<endl; cin>>year>>month>>day; t=shijian(year,month,day); cout<<year<<"年"<<month<<"月"<<day<<"是本年第"<<t<<"天"<<endl; cout<<"我相信这将是最美好的一天."<<endl; } int shijian(int year,int month,int day) { int t; if(year%4==0&&year%100!=0||year%400==0) { switch(month) { case 1: t=day; break; case 2: t=day+31; break; case 3: t=day+31+29; break; case 4: t=day+31+29+31; break; case 5: t=day+31+29+31+30; break; case 6: t=day+31+29+31+30+31; break; case 7: t=day+31+29+31+30+31+30; break; case 8: t=day+31+29+31+30+31+30+31; break; case 9: t=day+31+29+31+30+31+30+31+31; break; case 10: t=day+31+29+31+30+31+30+31+31+30; break; case 11: t=day+31+29+31+30+31+30+31+31+30+31; break; case 12: t=day+31+29+31+30+31+30+31+31+30+31+30; break; } return t; } else { switch(month) { case 1: t=day; break; case 2: t=day+31; break; case 3: t=day+31+28; break; case 4: t=day+31+28+31; break; case 5: t=day+31+28+31+30; break; case 6: t=day+31+28+31+30+31; break; case 7: t=day+31+28+31+30+31+30; break; case 8: t=day+31+28+31+30+31+30+31; break; case 9: t=day+31+28+31+30+31+30+31+31; break; case 10: t=day+31+28+31+30+31+30+31+31+30; break; case 11: t=day+31+28+31+30+31+30+31+31+30+31; break; case 12: t=day+31+28+31+30+31+30+31+31+30+31+30; break; } return t; } }