0 题面
题目描述
定义一个结构体变量(包括年、月、日)。计算该日在本年中是第几天,注意闰年问题。
输入格式
年月日
输出格式
当年第几天
样例输入
2000 12 31
样例输出
366
1 分析
这个题看上去是一个不难的题。因为其中的知识都很基础:
- 定义一个结构体
- 判断闰年
- 计算累加按月的天数
#include<iostream>
using namespace std;
typedef struct calendar
{
int year;
int month;
int day;
} calendar;
bool isLeap(int year)
{
return (year % 4 == 0 && year % 100 != 0 || year % 400 == 0);
}
const int monthDay[12]
{
31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
};
int indDay(calendar cale)
{
int ind = 0;
for (int i = 0; i < cale.month-1; ++i)
{
ind += monthDay[i];
}
ind += cale.day;
if (isLeap(cale.year) && cale.month > 2)
{
ind++;
}
return ind;
}
int main()
{
calendar cale;
cin >> cale.year;
cin >> cale.month;
cin >> cale.day;
cout << indDay(cale) << endl;
return 0;
}
对于新手来说,容易出错的地方在于:
闰年判断:
bool isLeap(int year)
{
return (year % 4 == 0 && year % 100 != 0 || year % 400 == 0);
}
闰年的判断条件是:
- 当年份不能被100整除时,年份数能被4整除;
- 当年份数能被100整除时,必须能被400整除。
按月累加天数:
- 加上前面月份的整月天数(注意不能把当月的整月天数累加上去,考查边界控制);
for (int i = 0; i < cale.month-1; ++i)
{
ind += monthDay[i];
}
- 加上当月的天数。
当是闰年时:
- 超过2月的天数计算时要加1(容易漏掉);
- 不超过2月的天数计算时别加1(容易对不超过2月的月份也加上1)。
【水平所限,错漏难免,创作不易,轻喷勿骂】