gpt4 book ai didi

c++ - 两个日期之间的总天数 C++

转载 作者:行者123 更新时间:2023-11-30 02:28:37 25 4
gpt4 key购买 nike

我正在尝试解决要求我给出两个日期之间的总天数的问题。

我必须处理这两个日期之间的一些问题,例如闰年和用户输入年份的方式。 (例如,如果您输入 1 和 17,代码仍然会给出 16 年的差异(2017 - 2001 = 16)。我不应该在 main() 函数中更改任何内容.

这是我的代码。

 #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;
}

当我运行这段代码时,它说“date”和“date”之间的二进制运算无效

现在,我假设当我初始化 int duration = end - start 时,我应该得到一个数字。我想我在这里做错的是我未能将(结束 - 开始)日期类型转换为整数。我以为我的函数 getDifference 已经解决了这个问题,但显然它没有。

最佳答案

接受挑战。

使用这个 free, open-source, header-only date library :

#include "date.h"
#include <iostream>

namespace me
{

class date
{
::date::sys_days tp_;
public:
date(int month, int day, int year)
: tp_{::date::year(year)/month/day}
{}

friend
int
operator-(const date& x, const date& y)
{
return (x.tp_ - y.tp_).count();
}
};

} // namespace me

using namespace std;
#define date me::date

int main()...

关于c++ - 两个日期之间的总天数 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40558353/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com