日期相关的题目
- 1. 计算日期到天数转换
- 2. 日期累加
- 3. 打印日期
- 4. 日期差值
1. 计算日期到天数转换
输出示例:
思路:计算前n-1个月的天数在加上这个月的天数。
#include <iostream>
using namespace std;
int main() {
int year, month, day;
cin >> year >> month >> day;
int month_day[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
int i = 0;
int days = 0;
for (i = 0; i < month; i++)
{
days += month_day[i];
}
days += day;
if(month > 2 && (((year % 4 == 0) && (year % 100 != 0)) || (year % 400) == 0))
{
days += 1;
}
cout << days;
return 0;
}
2. 日期累加
输出示例:
思路:直接加到天上,在进位求出日期
#include <iostream>
using namespace std;
int GetMonthDay(int year ,int month)
{
int months[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
int day = months[month];
if (month == 2 &&( ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)))
{
day++;
}
return day;
}
int main() {
int n = 0;
cin >> n;
int year = 0,month = 0, day = 0,num;
while (n-- && (cin >> year >> month >> day >> num) )
{
day += num;
while (day > GetMonthDay(year,month))
{
day -= GetMonthDay(year,month);
month++;
if (month == 13)
{
month = 1;
year++;
}
}
printf("%04d-%02d-%02d\n", year, month, day);
}
}
3. 打印日期
输出示例:
思路:从这年的1月1开始加,但是注意要要减掉一天,比如:求这一年的第一天的日期,就是1月1号,也可以理解为从1月0号开始加,所以直接加到天上,在进位求日期
#include <iostream>
using namespace std;
int GetMonthDay(int year,int month)
{
int months[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
int day = months[month];
if (month == 2 && ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0) ))
{
day += 1;
}
return day;
}
int main() {
int year = 0;
int n = 0;
while (cin >> year >> n) {
//从这年的1月1开始加,但是要减一天
int month = 1;
int day = n;//1 + n - 1
while (day > GetMonthDay(year,month) )
{
day -= GetMonthDay(year,month);
month++;
if (month == 13)
{
year++;
month = 1;
}
}
printf("%4d-%02d-%02d\n",year,month,day);
}
}
4. 日期差值
输出示例:
思路:直接从这天开始加,加到相等为止,每加一天就记一次数。
#include <iostream>
using namespace std;
int GetMonthDay(int year,int month)
{
int months[] = {0,31,28,31,30,31,30,31,31,30,31,30,31};
int day = months[month];
if (month == 2 && (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)))
{
day++;
}
return day;
}
void Add(int& year,int& month,int& day)
{
day += 1;
while (day > GetMonthDay(year,month))
{
day -= GetMonthDay(year,month);
month++;
if (month == 13)
{
month = 1;
year++;
}
}
}
int main() {
int year1,month1,day1;
scanf("%4d%2d%2d",&year1,&month1,&day1);
int year2,month2,day2;
scanf("%4d%2d%2d",&year2,&month2,&day2);
int count = 0;
int flag = 0;
if (year2 > year1)
{
flag = 1;
}
else if (year1 == year2 && month1 < month2)
{
flag = 1;
}
else if (year1 == year2 && month1 == month2 && day1 < day2)
{
flag = 1;
}
if (flag == 1)
{
swap(year1,year2);
swap(month1,month2);
swap(day1,day2);
}
while (!(year1 == year2 && month1 == month2 && day1 == day2))
{
Add(year2,month2,day2);
count++;
}
cout << count + 1;
}