我试图解决一个问题,要求我给出两个日期之间的总天数。我必须关注这两个日期之间的一些问题,如闰年和用户输入年份的方式。 (例如,如果你输入1和17,代码仍然会给你16年的差异(2017 - 2001 = 16)。我不应该改变main()函数中的任何东西。这里是我的代码。2个日期之间的总天数C++
#include <iostream>
#include <cmath>
using namespace std;
class date
{
private:
int m;
int d;
int y;
public:
date(int, int, int);
int countLeapYears(date&);
int getDifference(date&);
int operator-(date&);
};
int main()
{
int day, month, year;
char c;
cout << "Enter a start date: " << endl;
cin >> month >> c >> day >> c >> year;
date start = date(month, day, year);
cout << "Enter an end date: " << endl;
cin >> month >> c >> day >> c >> year;
date end = date(month, day, year);
int duration = end-start;
cout << "The number of days between those two dates are: " <<
duration << endl;
return 0;
}
date::date(int a, int b, int c)
{
m = a;
d = b;
y = c;
}
const int monthDays[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31,
30, 31};
int date::countLeapYears(date& d)
{
int years = d.y;
if (d.m <= 2)
years--;
return years/4 - years/100 + years/400;
}
int date::getDifference(date& other)
{
int n1 = other.y*365 + other.d;
for (int i=0; i<other.m - 1; i++)
{
n1 += monthDays[i];
n1 += countLeapYears(other);
}
return n1;
}
int date::operator-(date& d) {
int difference = getDifference(d);
return difference;
}
我有一个问题与我上面的代码,我需要你的帮助,请。当我运行它,它说:“日期”和“日期”之间的无效的二进制运算。现在,我想,当我初始化INT duration = end - start,我应该得到一个数字,我猜我在做什么错在这里是我没有把(结束 - 开始)日期类型转换为整数,我认为我的函数getDifference已经处理了这个问题。 ,似乎我没有照顾这个问题。
'2007 - 2001'是同样的事情'7 - 1',我实在看不出有什么冒险有关。 –
我不明白你在说什么。 –
你的问题很难理解。你的意思是你应该接受输入'7',就好像用户输入了'2007'一样吗?如果是这样,只需检查输入的年份是否小于'2000',并在这种情况下添加'2000'。 – DUman