您的位置:首页 > 编程语言 > C语言/C++

c++程序 计算两个日期相差的天数

2015-07-11 16:28 555 查看

#include <iostream>

#include <string>

#include <cmath>

using namespace std;

struct Date{

int y;//year

int m;//month

int d;//day in month

};

int isLeap(int y)

{

return y%4==0 && y%100==0 || y%400==0;

}

int daysOfMonth(Date d)

{

int days[12]={31,0,31,30,31,30,31,31,30,31,30,31};

if(d.m!=2)

return days[d.m-1];

else

return 28+isLeap(d.y);

}

int daysOfDate(Date d)

{

int days=0;

for(int y=1;y<=d.y;y++)

days+=365+isLeap(y);

for(int m=1;m<d.m;m++)

days+=daysOfMonth(d);

days+=d.d;

return days;

}

int main()

{

int a;

Date d1,d2;

cout << "Input 2 days days(yyyy mm dd):" << endl;

cin >> d1.y >> d1.m >> d1.d ;

cout << d1.y << "-" << d1.m << "-" << d1.d << endl;

int days1=daysOfDate(d1);

cout << "days1=" << days1 << endl;

cin >> d2.y >> d2.m >> d2.d ;

cout << d2.y << "-" << d2.m << "-" << d2.d << endl;

int days2=daysOfDate(d2);

cout << "days2=" << days2 << endl;

cout << "days distance is " << fabs(days1- days2) << endl;

return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: