题目描述:
有两个日期,求两个日期之间的天数,如果两个日期是连续的我们规定他们之间的天数为两天。
输入:
有多组数据,每组数据有两行,分别表示两个日期,形式为YYYYMMDD
输出:
每组数据输出一行,即日期差值
样例输入:
20130101
20130105
样例输出:
5
本文来自 xsj_blog 的CSDN 博客 ,全文地址请点击:https://blog.csdn.net/xsj_blog/article/details/51988328?utm_source=copy
#include <iostream>
#include <string>
#include <cmath>
using std::cin;
using std::cout;
using std::endl;
using std::string;
int month[13][2] = {{0, 0}, {31, 31}, {28, 29}, {31, 31}, {30, 30}, {31, 31}, {30, 30}, {31, 31}, {31, 31}, {30, 30}, {31, 31}, {31, 31}};
bool comp(int y1, int m1, int d1, int y2, int m2, int d2)
{
if (y1 != y2)
{
return y1 > y2;
}
else if (y1 == y2 && m1 != m2)
{
return m1 > m2;
}
else if (y1 == y2 && m1 == m2 && d1 != d2)
{
return d1 > d2;
}
}
int ryear(int year)
{
if ( (year % 4 == 0 && year % 100 == 0) || year % 400 == 0)
{
return true;
}
else
{
return false;
}
}
int main()
{
string s1, s2;
cin >> s1 >> s2;
int y1, m1, d1, y2, m2, d2;
y1 = (s1[0] - '0') * 1000 + (s1[1] - '0') * 100 + (s1[2] - '0') * 10 + (s1[3] - '0');
m1 = (s1[4] - '0') * 10 + (s1[5] - '0');
d1 = (s1[6] - '0') * 10 + s1[7] - '0';
y2 = (s2[0] - '0') * 1000 + (s2[1] - '0') * 100 + (s2[2] - '0') * 10 + (s2[3] - '0');
m2 = (s2[4] - '0') * 10 + (s2[5] - '0');
d2 = (s2[6] - '0') * 10 + (s2[7] - '0');
bool ifcomp = false; //if y1 > y2
ifcomp = comp(y1, m1, d1, y2, m2, d2);
int tempy = 0;
int tempm = 0;
int tempd = 0;
if (ifcomp)
{
tempy = y1;
y1 = y2;
y2 = tempy;
tempm = m1;
m1 = m2;
m2 = tempm;
y2 = tempy;
tempd = d1;
d1 = d2;
d2 = tempd;
}//y1, m1, d1 < y2, m2, d2
int ty, tm, td = 0;
int ry = 0;
int total = 1;
while (y1 < y2 || m1 < m2 || d1 < d2)
{
d1++;
if (d1 == month[m1][ryear(y1)] + 1)
{
m1++;
d1 = 1;
}
if (m1 == 13)
{
y1++;
m1 = 1;
}
total++;
}
cout << total;
}
又遇到了输入输出问题,这道题只有当我输入20130101 20130105才有输出结果,输入其他,都没有输出结果。
// Q700791.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <cstdio>
int a[13][2]={{0,0},{31,31},{28,29},{31,31},{30,30},{31,31},
{30,30},{31,31},{31,31},{30,30},{31,31},{30,30},{31,31}};
bool isLeap(int year){
return (year%4==0&&year%100!=0||year%400==0);
}
int main(){
int time1,y1,m1,d1;
int time2,y2,m2,d2;
int ans = 1;
while(scanf("%d%d",&time1,&time2)!=EOF){
y1=time1/10000;
y2=time2/10000;
m1=time1%10000/100;
m2=time2%10000/100;
d1=time1%100;
d2=time2%100;
if(time1>time2){
int temp=time1;time1=time2;time2=temp;
}
while(!(y1==y2&&m1==m2&&d1==d2)){
d1++;
if(d1>a[m1][isLeap(y1)]){
d1=1;m1++;
if(m1>12){
m1=1;
y1++;
}
}
ans++;
}
printf("%d",ans);
}
return 0;
}
我测试了20130101 20130105, 20130101 20130106,20130101 20130201都没有输出问题,不是到你说的除了1号到5号其他的输入都没输出是什么意思