【问题标题】:Problem of calculating the days between two dates in c++ using class of Date when the first date is bigger than second date当第一个日期大于第二个日期时,使用 Date 类计算 C++ 中两个日期之间的天数的问题
【发布时间】:2022-12-03 07:29:27
【问题描述】:

当第一个日期大于第二个日期时,它不计算。 例如:第一次约会 22/10/2022 第二个日期:15/10/2022

#include <iostream>
#include <cstdlib>
using namespace std;
class Date {
    public:
        Date(int d, int m, int y);
        void set_date(int d, int m, int y);
        void print_date();
        void inc_one_day();
        bool equals(Date d);
        int get_day() { return day; }
        int get_month() { return month; }
        int get_year() { return year; }
    private :
    int day;
    int month;
    int year;
};

bool is_leap_year(int year)
{
    int r = year % 33;
    return r == 1 || r == 5 || r == 9 || r == 13 || r == 17 || r == 22 || r == 26 || r == 30;
}

int days_of_month(int m, int y){
    if (m < 7)
        return 31;
    else if (m < 12)
        return 30;
    else if (m == 12)
        return is_leap_year(y) ? 30 : 29;
    else
        abort();
}

void Date::inc_one_day(){
    day++;
    if (day > days_of_month(month, year)) {
        day = 1;
        month++;
        if (month > 12) {
            month = 1;
            year++;
        }
    }
}
bool Date::equals(Date d) {
    return day == d.day && month == d.month && year == d.year;
}

int days_between(Date d1, Date d2){
    int count = 1;
    while (!d1.equals(d2)){
        d1.inc_one_day();
        count++;
    }
    return count;
}

Date::Date(int d, int m, int y){
    cout << "constructor called \n";
    set_date(d, m, y);
}

void Date::set_date(int d, int m, int y){
    if (y < 0 || m < 1 || m>12 || d < 1 || d > days_of_month(m, y))
    abort();
    day = d;
    month = m;
    year = y;
}

void Date::print_date(){
    cout << day << '/' << month << '/' << year<<endl;
}

int main(){
    Date bd(22, 12, 1395);
    Date be(15, 12, 1395);
    cout << '\n';
    int i;
    i= days_between(bd, be);
    cout << i << endl;
}

这是我的代码。 我见过很多计算两个日期之间的天数的代码,但他们没有使用 Date 类。 我怎么解决这个问题?你们能帮帮我吗?对不起,我是 C++ 的新手,所以我的问题可能很简单。

【问题讨论】:

  • 建议:在调试器中单步执行代码。 days_between() 是干什么的(不是理论上,实际上是一步一步)? while () 循环中有什么?
  • 如果除了 Date::equals 之外还实现了 Date::later_than,那就太好了。然后你可以这样说:if (d1.later_than(d2)) { return days_between(d2, d1); }

标签: c++ class date visual-c++ days


【解决方案1】:

更容易的是编写一个函数来计算自 0000 年以来发生的总天数。之后,您可以简单地将它们彼此相减并返回它们之间的总天数。

【讨论】:

    猜你喜欢
    • 2023-03-29
    • 1970-01-01
    • 2020-11-13
    • 2021-09-11
    • 2015-02-26
    • 2019-09-27
    相关资源
    最近更新 更多