给出年、月、日,计算该日是该年的第几天。
解:程序:
#include<iostream>
using namespace std;
int main()
{
int sum_day(int , int);
int leap(int year);
int year,month,day,days;
cout <<"input date(year,month,day):";
cin>>year>>month>>day;
cout << year<<"/"<<month<<"/"<<day;
days = sum_day(month, day);
if (leap(year) && month >= 3)
{
days += 1;
}
cout <<" is the " <<days<< "th day in this year." <<endl;
system("pause");
return 0;
}
int sum_day(int month, int day)
{
int i;
int day_tab[12] = { 31,28,31,30,31,30,31,31,30,31,30,31 };
for (i = 0; i < month - 1; i++)
//输入的时候已经知道所求最后一个月有多少天,故i < month - 1
{
day += day_tab[i];
}
return (day);
}
int leap(int year)//判断是否为闰年
{
int leap;
leap = year % 4 == 0 && year % 100 != 0 || year % 400 == 0;
return(leap);
}
结果:
input date(year,month,day):2016 3 24
2016/3/24 is the 84th day in this year.
请按任意键继续. . .