Answer to Question #283447 in C++ for Sachin

Question #283447

Create a Date class with three



integer instance variables named



day,month,year.It has a constructor



with three parameters for initializing



the instance variables,and it has one



method named daysSinceJan1(). It



computes and returns the number of



days since January 1 of the same



year,including January 1 and the day



in the Date object.



For example,if day is a Date object



with day=1,month=3,and



year=2000,then the



calldate.daysSinceJan1() should



return 61 since there are 61 days



between the dates of January



1,2000,and March 1,2000,including



January 1 and March 1. Don’t forget



to consider leap years.

1
Expert's answer
2021-12-29T02:19:38-0500
#include <iostream>
#include <string>
using namespace std;


class Dates
{
private:
    int month, day, year;
    struct Date
    {
        int d, m, y;
    };
    const int daysOfMonths[12] = {31, 28, 31, 30, 31, 30,
                               31, 31, 30, 31, 30, 31};


public:
    Dates();
    Dates(int month, int day, int year)
    {
        this->day = day;
        this->month = month;
        this->year = year;
    }
    ~Dates() {}
    void setDay(int day)
    {
        this->day = day;
    }
    void setMonth(int month)
    {
        this->month = month;
    }
    void setYear(int)
    {
        this->year = year;
    }
    int LeapYear(Date d)
    {
        int years = d.y;
        if (d.m <= 2)
            years--;


        return years / 4 - years / 100 + years / 400;
    }
    int getAnswer()
    {
        Date dt1, dt2;
        dt2.d = this->day;
        dt2.m = this->month;
        dt2.y = this->year;
        dt1.y = this->year;
        dt1.d = 1;
        dt1.m = 1;
        long int n1 = dt1.y * 365 + dt1.d;


        for (int i = 0; i < dt1.m - 1; i++)
            n1 += daysOfMonths[i];


        n1 += LeapYear(dt1);
        long int n2 = dt2.y * 365 + dt2.d;
        for (int i = 0; i < dt2.m - 1; i++)
            n2 += daysOfMonths[i];
        n2 += LeapYear(dt2);


        return (n2 - n1);
    }
};

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog