I have a program that uses two functions I have defined inside a class. My class works fine, but my program always returns an amount that is some amount of days off. There is more error when the dates are farther apart. My code is designed to in one function calculate the total amount of days since 1582, and another function subtracts the higher amount from the lesser. Where am I getting the error from? I know it may not be the most efficient way to do things (cpu wise) but can someone find where my logic is messed up? This accounts for leap years as well. I have been checking my program against a website http://www.timeanddate.com/date/durationresult.html
int Date::totalDays()
{
int totalDays = 0;
int daysInMonth[]={0,31,28,31,30,31,30,31,31,31,31,30,31};
totalDays += day;
for (int i = month-1; i > 0; i--)
{
totalDays += daysInMonth[i];
}
for (int i = year-1; i > 1582; i--)
{
if(year % 100 == 0)
{
if(year % 400 == 0)
totalDays += 366;
else
totalDays += 365;
}
else
{
if(year % 4 == 0)
totalDays += 366;
else
totalDays += 365;
}
}
return totalDays;
}
int Date::daysBetween(Date other)
{
if (this->totalDays() > other.totalDays())
return this->totalDays() - other.totalDays();
else
return other.totalDays() - this->totalDays();
}
Thank you.
Problem 1:
int daysInMonth[]={0,31,28,31,30,31,30,31,31,31,31,30,31};
should be
int daysInMonth[]={0,31,28,31,30,31,30,31,31,30,31,30,31};
// ^^
Problem 2:
if the current year is a leap-year, and month is greater than 2, you'll also need to add one day to account for February 29th of the current year.
Related
I am trying to solve this problem:
Write a program to calculate how many days are required for a snail to climb up a wall. A snail climbs on a wall, it starts at the bottom and climbs up n meters a day. Regretfully, every night it slides m meters down. Given the height of the wall H, write a program to calculate how many days required for the snail to reach the top of the wall.
If the snail will never be able to reach the top of the wall print: Fail.
This is my attempt to solve this problem:
int numDays(int wall_height, int meters_per_day, int meters_down_per_day) {
int current_height = 0;
int days = 0;
while (current_height != wall_height) {
if (current_height + (meters_per_day - meters_down_per_day) >= wall_height) {
break;
}else {
days += 1;
current_height += meters_per_day - meters_down_per_day;
}
}
return days;
}
int main()
{
int wall_height = 30;
int meters_per_day = 3;
int meters_down = 2;
if (meters_down >= meters_per_day) {
cout << "Fail" << endl;
}else {
cout << numDays(wall_height, meters_per_day, meters_down) << endl;
}
return 0;
}
My solution returns 29 days, but the answer is 28 days because once the snail has climbed 27 meters after 27 days, it will simply climb the remaining 3 meters to the top on the 28th day.
What I am doing wrong to generate the wrong output? Thanks!
Your error is that you are only checking if the snail has reached the top of the wall after it has climbed up and down. You even say this yourself. Instead you should check the height after the climb up only
Here's loop that does that.
for (;;) {
current_height += meters_per_day;
if (current_height >= wall_height) {
break;
current_height -= meters_down_per_day;
days += 1;
}
For me, here is the right implementation of your numDays function :
int numDays(int wall_height, int meters_per_day, int meters_down_per_day) {
int current_height = 0;
int days = 1;
while (current_height != wall_height) {
current_height += meters_per_day;
if(current_height >= wall_height)
break;
days += 1;
current_height -= meters_down_per_day;
}
return days;
}
the answer is 28 days because once the snail has climbed 27 meters after 27 days, it will simply climb the remaining 3 meters to the top on the 28th day
To do this, you need to increment first the current_height before testing if the snail is on the top of the wall.
I think the day counter must start at 1 because the first day of iteration is the day 1 (I don't know if the explanation is really clear).
Here's my simple Python program to solve the problem that implements the given conditions:
def num_days(h, n, m):
days = 0
position = 0
while n < h:
if m >= n:
break
days += 1
position += n
if position >= h:
return days
position -= m
if days == 0:
days = 'Fail'
return days
You can call the function num_days with h, n, and m as arguments to get the number of days required for the snail to reach the top of the wall.
For example:
num_days(11, 3, 2)
return
9
num_days(5, 3, 1)
return
2
num_days(5, 0, 1)
return
Fail
I'm a novice in coding...
I've written a code in C++ to calculate the date after adding new numbers to date, month, and year. However, it's become too long and my computer can't process it if the date goes over 50.
Could you give me a few tips if there was a way to shorten this?
#include <iostream>
class Date{
int year; int month; int day;
}
public:
void set_date(int _year, int _month, int _day){
year=_year;
month=_month;
day=_day;
}
void add_day(int inc){
day+=inc;
}
void add_month(int inc){
month+=inc;
}
void add_year(int inc){
year+=inc;
}
void get_date(){
while (day>31){
if ((year%4)==0 && month==2 && day > 29){
month+=1;day-=29;
}
else if(month==2 && day > 28){
month+=1;day-=28;
}
else if((day>30)&&(month==4||month==6||month==9||month==11)){
month+=1;day-=30;
}
else if((day>31)&&(month==3||month==5||month==7||month==8||month==10||month==12||month==1)){
month+=1;day-=31;
}
}
if (month>12){
year+=month/12;
month=month%12;
}
std::cout<<"year"<<year<<std::endl;
std::cout<<"month"<<month<<std::endl;
std::cout<<"day"<<day<<std::endl;
}
int main(){
Date date;
date.set_data(191,2,10);
date.add_day(60);
date.add_month(10);
date.add_year(3);
date.get_date();
return 0;
}
When I run your code it loops forever with day=39 and month=13, which is a condition you don't check for. You might want to move the whole if (month>12) into your loop, so that the months get corrected while processing the days. You also want to add an else that stops the loop:
bool doneProcessing = false;
do
{
if ((year % 4) == 0 && month == 2 && day > 29)
{
month += 1;
day -= 29;
}
else if (month == 2 && day > 28)
{
month += 1;
day -= 28;
}
else if ((day > 30) && (month == 4 || month == 6 || month == 9 || month == 11))
{
month += 1;
day -= 30;
}
else if ((day > 31) && (month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12 || month == 1))
{
month += 1;
day -= 31;
}
else
{
doneProcessing = true;
}
if (month > 12)
{
year += month / 12;
month = month % 12;
}
}
while (!doneProcessing);
I didn't check the validity of your semantics, but I did notice one thing: When you have month=2 and day=30, you'd want to process that as well, but you only check day>31, thus I changed the loop to simply run until the else is hit (all days are valid now).
With this change your code properly terminates after printing this result:
year195
month2
day8
PS: With a debugger you can easily and quickly find such issues. See What is a debugger and how can it help me diagnose problems?
And yes this is an assignment-- So please don't post solutions, but detailed pseudocodes are extremely helpful!
I already have a program in C++ that accepts a date from the user and will determine if it is a leap year or not.
Here is my leap year function so far (I do hope that this is the correct logic):
bool isLeapYear (int year){
int leapYear = 0;
//leapyear = 1 when true, = 0 when false
if ((year%400 == 0) && (year%100 != 100)) {
leapYear = 1;
}
else if (year%4 == 0) {
leapYear = 1;
}
else {
leapYear = 0;
}
if (leapYear == 1) {
return 1;
}
else {
return 0;
}
}
Here is a paraphrase of what I must do next:
You MUST use a loop that adds months one at a time to an accumulated sum.
Don't use any hardcoded values
Such as 152 for the first 5 months in a leap year
And to clarify, this is my first programming class and have been in this C++ class for just about a month now.
So it would be greatly appreciated if anyone could help me figure out how to do the loop statements to add the number of the months?
(IE: 12/31/2013 should be "365" in a non leap year, and "366" in a leap year).
I know this is wrong but this is what I have so far for a function "dayNumber" that simply return the number of days in the year to the main function (which is calling the dayNumber function):
int dayNumber (int day, int month, int year){
//variable declarations
int sumTotal = 0;
for ( int loop = 1; loop < month; loop++) {
sumTotal = (( month-1 ) * 31);
sumTotal = sumTotal + day + 1;
if ( (loop==4) || (loop=6) || (loop=9) ||
(loop==11) ) {
sumTotal = ( sumTotal - 1 );
}
else if ( isLeapYear(year) == 1 ) {
sumTotal = (sumTotal - 2);
}
else {
sumTotal = (sumTotal - 3);
}
}
return sumTotal;
}
I started to mess around with it to get to a proper value for days I knew but it kind of messed it up more, haha.
If anyone has any guidance on how to appropriately do a loop, I would be extremely greatful!:)
EDIT:
Alright, I think I may have answered my own question.
int dayNumber (int day, int month, int year){
//variable declarations
int sumTotal = 0;
for ( int loop = 1; loop < month; loop++) {
sumTotal = ( sumTotal + 31 );
if ( (loop==4) || (loop==6) || (loop==9) ||
(loop==11) ) {
sumTotal = ( sumTotal - 1 );
}
}
if ((month !=2) && (month > 1)) {
if (isLeapYear(year) ==1) {
sumTotal = ( sumTotal - 2 );
}
else {
sumTotal = ( sumTotal - 3);
}
}
else {
sumTotal = sumTotal;
}
sumTotal = sumTotal + day;
return sumTotal;
}
I definitely need to work on my loops.
I appreciate letting me know that my '=' should have been '=='!
I believe this is an appropriate code using a simple enough loop?
I will test some more dates. I've only tested the few provided on the class site so far.
I can't answer my own posts, I don't have enough reputation.
I know an answer has been accepted, but it took me some time writing my own, let's see if it can adds some informations overall.
Let's review this slowly.
First, your isLeapYear() function isn't completely right.
Without delving into the algorithm part, two or three things can be improved.
You're returning a bool, yet your return statements are returning ints. This isn't wrong in itself, but using the true and false keywords can improve the readability and consistency.
Instead of creating, assigning and returning a variable, you should instantly return your result.
Add spaces around your operators : year%400 should become year % 400.
Now your code.
This condition :
if ((year%400 == 0) && (year%100 != 100))
... especially this part :
(year%100 != 100)
Isn't doing what you expect.
Overall, the algorithm is as follow :
if year is not divisible by 4 then common year
else if year is not divisible by 100 then leap year
else if year is not divisible by 400 then common year
else leap year
Translating it in code:
/**/ if (year % 4 != 0)
return false;
else if (year % 100 != 0)
return true;
else if (year % 400 != 0)
return false;
else
return true;
Now let's simplify this a bit:
/**/ if (year % 4 == 0 && year % 100 != 0)
return true;
else if (year % 400 == 0)
return true;
else
return false;
Again:
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
return true;
else
return false;
And finally, the whole boolean expression can be directly returned:
return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
Now that your function is correct, let's try an algorithm to your dayNumber function :
If the date provided in parameters is considered correct, then the algorithm is quite simple :
Start sum from 0
Loop from 1 to month excluded
If month is Frebruary then add 29 if isLeapYear returns true, else 28
If month is January, March, May, July, August, October or December add 31
Else add 30
Add day to sum.
I know that giving detailed pseudocode helps more than a solution, but I'm not that good of a teacher yet :/ Good luck with this answer, and get some sleep when you're done :)
I'm assuming that dayNumber(8, 3, 1914) is supposed to return the ISO day number of 1914, March 8th.
What you want to do is the following:
procedure dayNumber(theDay, theMonth, theYear):
set answer to 1 // the first day of the year is day 1
for every month 'thisMonth', up to and excluding theMonth:
increment answer by the number of days in thisMonth
increment answer by (theDay - 1) // the first day of the month is monthday 1
return answer
In the iteration statement (or 'loop body'), there are three cases:
February: if it's a leap year, increment thisMonth by 29, otherwise increment by 28.
Short months (April, June, September, November): increment by 30 days.
Otherwise, long months (January, March, May, July, August, October, December): increment by 31 days.
This translates to:
if (thisMonth == 2) {
// February
if (isLeapYear(theYear))
thisMonth += 29;
else
thisMonth += 28;
} else if (thisMonth == 4 || thisMonth == 6 || thisMonth == 9 || thisMonth == 11) {
// Short month
thisMonth += 30;
} else {
// Long month
thisMonth += 31;
}
(Note: X += Y is, or should be, short for X = X + Y.)
The loop logic you use looks mostly correct to me, except for 1) off-by-one errors because you start with day 0, and 2) adding the monthday inside the loop rather than outside of it:
int dayNumber (int theDay, int theMonth, int theYear) {
int result = 1;
for (int thisMonth = 1; thisMonth < theMonth; thisMonth++) {
/* ... see above ... */
}
return result + theDay - 1;
}
Now, about making the iteration statement prettier, there are basically two ways (and if your course hasn't yet covered them, I of course recommend against using them in an answer). One is using a switch statement, but I'm really not a fan of them, and it doesn't provide much benefit over the code I already gave. The other would be to use arrays:
int dayNumber (int theDay, int theMonth, int theYear) {
int monthDays[12] = { 31, 28, 31, 30, 31, 30, 31
, 31, 30, 31, 30, 31 }
int result = 1;
for (int thisMonth = 1; thisMonth < theMonth; thisMonth++) {
if (thisMonth == 2 && isLeapYear(theYear))
// Special case: February in a leap year.
result += 29;
else
/* Take the month length from the array.
* Because C++'s array indices begin at 0,
* but our first month is month 1,
* we have to subtract one from thisMonth.
*/
result += monthDays[thisMonth - 1];
}
return result + theDay - 1;
}
#include <ctime>
static int GetDaysInMonthOfTheDate(std::tm curDate)
{
std::tm date = curDate;
int i = 0;
for (i = 29; i <= 31; i++)
{
date.tm_mday = i;
mktime(&date);
if (date1->tm_mon != curDate.tm_mon)
{
break;
}
}
return i - 1;
}
I was just wondering if anyone noticed i was doing something wrong with my code block. Ths program is supposed to be a test program that compares 2 dates. The function that im working on is supposed to return a 1 if the invoking date is greater, a -1 f the invoking date is less than, and a 0 if the invoking date is equal to the date in the parameter. My test Program :
#include <cstdlib>
#include <iostream>
#include <string>
#include "date.h"
using namespace std;
//date is initialized in a month/day/year format.
int main(int argc, char* argv[])
{
string* d;
date d1(4,1,4);
date d4(4,4,4);
int greaterTest = d4.compareTo(d1);
int lessTest = d1.compareTo(d4);
cout << greaterTest << endl; //i believe these two lines are printing out a
cout << lessTest << endl; //location in memory
cout<<&d <<endl;
system("pause");
return EXIT_SUCCESS;
}
The huge compareTo() function :
int date::compareTo (date another_date)
{
if (this->year == another_date.year && this->month == month && this->day < another_date.day) //if both year and month are the same, test to see if day is less
{
return -1;
}
else if (this->year == another_date.year && this->month == month && this->day > another_date.day) //if both year and month are the same, test to see if day is greater
{
return 1;
}
else if (this->year == another_date.year && this->month > month) //if the years are the same, test to see if the invoking month is greater
{
return 1;
}
else if (this->year == another_date.year && this->month < month) //if the years are the same, test to see if the invoking month is less
{
return -1;
}
else if (this->year > another_date.year) //test to see if the invoking year is greater
{
return 1;
}
else if (this->year < another_date.year) //test to see if the invoking year is less
{
return -1;
}
else if(this-> year == another_date.year && this-> month == another_date.month //test if the dates are exactly the same
&& this-> day == another_date.day)
{
return 0;
}
//else{ return 15;} //if none are true, return 15
}
the only problem im getting is when i try to change the day (the second parameter for date).
I'm not sure if this is the problem, since I can't test it... But, your compareTo function has this line:
this->month == month
Shouldn't it be:
this->month == another_date.month
?
In the first if statement and a few below it as well you have:
this->month == month
This is comparing month to itself, I think you meant:
this->month == another_date.month
Also you don't need to use the 'this' pointer all the time,
month == another_date.month
should suffice.
That might benefit from some early exit:
int date::compareTo (date another_date)
{
if (year > another_date.year) {
//the invoking year is greater
return 1;
}
if (year < another_date.year) {
//the invoking year is less
return -1;
}
// if we reached here, the years are the same. Don't need to compare them for the other cases
if (month > another_date.month) {
return 1;
}
if (month < another_date.month) {
return -1;
}
// if we reached here, the year and month are the same
if (day > another_date.day) {
return 1;
}
if (day < another_date.day) {
return -1;
}
// if we reached here, the year and month and day are the same
return 0;
}
Along the way, the cut+paste error just... disappeared, because that test became redundant.
Unless you're really set on doing an element-by-element comparison, I'd put each set of inputs into a struct tm, then use mktime to convert those to a time_t, and the compare the two time_ts directly. In a typical case, those will be a 32- or 64-bit integer of the number of seconds since midnight Jan 1, 1970, so after the conversion, comparison becomes trivial.
I didn't find your bug in your original code because it was too hard for me to read. I suppose that's why you didn't find it either.
This alternative might be easier to read, and easier to prove correct:
// untested
int date::compareTo (date another_date)
{
if (year < another_date.year) return -1;
if (year > another_date.year) return 1;
if (month < another_date.month) return -1;
if (month > another_date.month) return 1;
if (day < another_date.day) return -1;
if (day > another_date.day) return 1;
return 0;
}
I'm trying to figure out a way for my program to take a date (like February 2nd, 2003) and show the difference between the two with another date (like April 2nd, 2012), excluding leap years. So far I've only been able to figure it out if the dates are in the same month, just by subtracting the "day". In this program I use 2 sets of "month", "day" and "year" integers. I'm pretty much at a loss from where to go from here. This is a completely optional part of my assignment but I'd like to get an idea on how to get it to work. It seems like a hassle to me, but maybe there's a simple math formula I'm not thinking about?
Sorry, I don't have any pre-existing code for this part because the rest of the assignment just deals with having the user enter dates and then adding and subtracting a single day.
Using just the standard library, you can convert a moderately insane date structure into a count of seconds since an arbitrary zero point; then subtract and convert into days:
#include <ctime>
// Make a tm structure representing this date
std::tm make_tm(int year, int month, int day)
{
std::tm tm = {0};
tm.tm_year = year - 1900; // years count from 1900
tm.tm_mon = month - 1; // months count from January=0
tm.tm_mday = day; // days count from 1
return tm;
}
// Structures representing the two dates
std::tm tm1 = make_tm(2012,4,2); // April 2nd, 2012
std::tm tm2 = make_tm(2003,2,2); // February 2nd, 2003
// Arithmetic time values.
// On a posix system, these are seconds since 1970-01-01 00:00:00 UTC
std::time_t time1 = std::mktime(&tm1);
std::time_t time2 = std::mktime(&tm2);
// Divide by the number of seconds in a day
const int seconds_per_day = 60*60*24;
std::time_t difference = (time1 - time2) / seconds_per_day;
// To be fully portable, we shouldn't assume that these are Unix time;
// instead, we should use "difftime" to give the difference in seconds:
double portable_difference = std::difftime(time1, time2) / seconds_per_day;
Using Boost.Date_Time is a little less weird:
#include "boost/date_time/gregorian/gregorian_types.hpp"
using namespace boost::gregorian;
date date1(2012, Apr, 2);
date date2(2003, Feb, 2);
long difference = (date1 - date2).days();
It seems like a hassle to me, but maybe there's a simple math formula I'm not thinking about?
It is indeed a hassle, but there is a formula, if you want to do the calculation yourself.
Here is a complete code to calculating date difference in y/m/d.
Assuming that to and from are date types, and that months and days start from 1 (similar to Qt):
static int increment[12] = { 1, -2, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1 };
int daysInc = 0;
if (to.day() - from.day() < 0)
{
int month = to.month() - 2; // -1 from zero, -1 previous month.
if (month < 0)
month = 11; // Previous month is December.
daysInc = increment[month];
if ( (month == 1) && (to.year()%4 == 0) )
daysInc++; // Increment days for leap year.
}
int total1 = from.year()*360 + from.month()*30 + from.day();
int total2 = to.year()*360 + to.month()*30 + to.day();
int diff = total2 - total1;
int years = diff/360;
int months = (diff - years*360)/30;
int days = diff - years*360 - months*30 + daysInc;
// Extra calculation when we can pass one month instead of 30 days.
if (from.day() == 1 && to.day() == 31) {
months--;
days = 30;
}
I tried this algorithm and it is working okay. Let me know if you have troubles using/understanding it.
Since you are looking for mathematical formula , it will help you to find a solution to your problem. Let Y be the year,M be the month and D be the day. Do this calculation for both the dates.
Total = Y* 365 + M*30 + D ,then find the difference between 2 totals of the corresponding dates.
While multiplying 30 with M value ,you have to give the number of days in that month. You can do it with #define value or if loop. Similarly you can do for leap year too by multiplying 366 with Y .
Hope this will help u....
New answer for an old question:
chrono-Compatible Low-Level Date Algorithms
has formulas for converting a {year, month, day} triple to a serial count of days and back. You can use it to calculate the number of days between two dates like this:
std::cout << days_from_civil(2012, 4, 2) - days_from_civil(2003, 2, 2) << '\n';
which outputs:
3347
The paper is a how-to manual, not a library. It uses C++14 to demonstrate the formulas. Each formula comes with a detailed description and derivation, that you only have to read if you care about knowing how the formula works.
The formulas are very efficient, and valid over an extremely large range. For example using 32 bit arithmetic, +/- 5 million years (more than enough).
The serial day count is a count of days since (or prior to for negative values) New Years 1970, making the formulas compatible with Unix Time and all known implementations of std::chrono::system_clock.
The days_from_civil algorithm is not novel, and it should look very similar to other algorithms for doing the same thing. But going the other way, from a count of days back to a {year, month, day} triple is trickier. This is the formula documented by civil_from_days and I have not seen other formulations that are as compact as this one.
The paper includes example uses showing typical computations, std::chrono interoperability, and extensive unit tests demonstrating the correctness over +/- 1 million years (using a proleptic Gregorian calendar).
All of the formulas and software are in the public domain.
I'm not sure what platform are you on? Windows, Linux? But let us pretend that you would like to have a platform independent solution and the langugage is standard C++.
If you can use libraries you can use the Boost::Date_Time library (http://www.boost.org/doc/libs/1_49_0/doc/html/date_time.html)
If you cannot use libraries to solve your assignment, you will need to find a common simple ground. Maybe you could convert all the dates to seconds, or days substract them and then convert that back to the data again. Substracting days or months as integers will not help as it will lead to incorrect results unless you do not take into account the rest.
Hope that helps.
Like dbrank0 pointed it out. :)
There is another way round...
Given two dates, take the year of the earlier date as the reference year.
Then calculate no. of days between each of the two given dates and that 1/1/<that year>
Keep a separate function that tells the number of days elapsed till a specific month.
The absolute difference of those two no. of days will give the difference between the two given dates.
Also, do not forget to consider leap years!
The code:
#include<stdio.h>
#include<math.h>
typedef struct
{
int d, m, y;
} Date;
int isLeap (int y)
{
return (y % 4 == 0) && ( y % 100 != 0) || (y % 400 == 0);
}
int diff (Date d1, Date d2) //logic here!
{
int dd1 = 0, dd2 = 0, y, yref; //dd1 and dd2 store the <i>no. of days</i> between d1, d2 and the reference year
yref = (d1.y < d2.y)? d1.y: d2.y; //that <b>reference year</b>
for (y = yref; y < d1.y; y++)
if (isLeap(y)) //check if there is any leap year between the reference year and d1's year (exclusive)
dd1++;
if (isLeap(d1.y) && d1.m > 2) dd1++; //add another day if the date is past a leap year's February
dd1 += daysTill(d1.m) + d1.d + (d1.y - yref) * 365; //sum up all the tiny bits (days)
for (y = yref; y < d2.y; y++) //repeat for d2
if(isLeap(y))
dd2++;
if (isLeap(y) && d2.m > 2) dd2++;
dd2 += daysTill(d2.m) + d2.d + (d2.y - yref) * 365;
return abs(dd2 - dd1); //return the absolute difference between the two <i>no. of days elapsed past the reference year</i>
}
int daysTill (int month) //some logic here too!!
{
int days = 0;
switch (month)
{
case 1: days = 0;
break;
case 2: days = 31;
break;
case 3: days = 59;
break;
case 4: days = 90; //number of days elapsed before April in a non-leap year
break;
case 5: days = 120;
break;
case 6: days = 151;
break;
case 7: days = 181;
break;
case 8: days = 212;
break;
case 9: days = 243;
break;
case 10:days = 273;
break;
case 11:days = 304;
break;
case 12:days = 334;
break;
}
return days;
}
main()
{
int t; //no. of test cases
Date d1, d2; //d1 is the first date, d2 is the second one! obvious, duh!?
scanf ("%d", &t);
while (t--)
{
scanf ("%d %d %d", &d1.d, &d1.m, &d1.y);
scanf ("%d %d %d", &d2.d, &d2.m, &d2.y);
printf ("%d\n", diff(d1, d2));
}
}
Standard Input:
1
23 9 1960
11 3 2015
Standard Output:
19892
Code in action: https://ideone.com/RrADFR
Better algorithms, optimizations and edits are always welcome!
If you need to do it yourself, then one way to do this pretty easy is by converting dates into a Julian Day. You get formulas at that link, and from conversion on, you only work with floats, where each day is 1 unit.
I've made similar program but it count only days in border of one year or couple years
PS I'm in c++ programming only about two month
#include<iostream>
int calculateDaysInYears(int intYear, int endYear);
int checkYear(int intYear);
int checkMonth(int i, int intYear);
int getUserData()
{
int dayOrMonthOrYear;
std::cin >> dayOrMonthOrYear;
return dayOrMonthOrYear;
}
int calculateMonthInYears(int initialMonth, int endMonth, int initialYear)
{
//Подсчет дней начальной даты для варианта с несколькими годами
int x(0);
initialMonth++;
for (int i = initialMonth; i <= endMonth; i++)
x += checkMonth(i, initialYear);
return x;
}
int calculateMonth(int startMonth, int endMonth, int initialYear)
{
//Формула для подсчета кол-вa дней промежуточных месяцев
//Расчет в пределах года
startMonth++;
int x(0);
for (int i = startMonth; i < endMonth; i++)
x += checkMonth(i, initialYear);
return x;
}
int calculateMonthForEndYear(int endMonth, int endYear)
{
//Подсчет дней в конечном году
int x(0);
//Декремент кол-ва конечных месяцев для компенсации дней последнего месяца
--endMonth;
for (int i = 1; i <= endMonth; i++)
x += checkMonth(i, endYear);
return x;
}
int checkMonth(int i, int intYear)
{
if (i == 1 || i == 3 || i == 5 || i == 7 || i == 8 || i == 10 || i == 12)
return 31;
else
if (i == 2)
{
//Если год високосный, то делится на 4 и 400 без остатка, а на 100 с остатком
if ((intYear % 4 == 0) && (intYear % 100 != 0 ) || (intYear % 400 == 0))
return 29;
else
return 28;
}
else
return 30;
}
int calculateAmountOfDays(int initialDay, int initialMonth, int initialYear)
{
//Подсчет дней до конца стартового месяца
int month = checkMonth(initialMonth, initialYear);
int days = month - initialDay;
return days;
}
int allDays(int initilDays, int endDays, int midleMonth)
{
int totalDays;
//Подсчет всех дней от начала до конца
totalDays = midleMonth + initilDays + endDays;
return totalDays;
}
int checkYear(int intYear)
{
if ((intYear % 4 == 0) && (intYear % 100 != 0) || (intYear % 400 == 0))
return 366;//Високосный год
else
return 365;//Невисокосный год
}
int calculateDaysInYears(int intYear, int endYear)
{
//Начальное кол-во дней. Необходимо для запуска счетчика
int amountDays(0);
//Инкремент начального года для компенсации кол-ва дней промежуточных годов
intYear++;
for (int i = intYear; i < endYear; i++)
amountDays += checkYear(i);
return amountDays;
}
int main()
{
int initialDay;
int initialMonth;
int initialYear;
int endDay;
int endMonth;
int endYear;
std::cout << "Hello! I'm your calendar calculator." << std::endl <<
"Here some rules: " << std::endl <<
"you should enter a data like(d.m.y): 23.8.2020." << std::endl <<
"Also you can ask me to calculate for couple years or in border of one year. Good luck! " << std::endl;
std::cout << "" << std::endl;
//Начальная дата
std::cout << "Enter an initial day: ";
initialDay = getUserData();
std::cout << "Enter an initial month: ";
initialMonth = getUserData();
std::cout << "Enter an initial year: ";
initialYear = getUserData();
std::cout << "" << std::endl;//Пропуск строки
//Конечная дата
std::cout << "Enter an end day: ";
endDay = getUserData();
std::cout << "Enter an end month: ";
endMonth = getUserData();
std::cout << "Enter an end year: ";
endYear = getUserData();
//Проверка кол-ва годов
if ((endYear - initialYear) >= 1)
{
//Подсчет дней до конца начального года
int daysToTheEndOfStartYear = calculateMonthInYears(initialMonth, 12, initialYear) + calculateAmountOfDays(initialDay, initialMonth, initialYear);
//Подсчет дней до конца конечного месяца
int daysToTheEndOfEndYear = calculateMonthForEndYear(endMonth, endYear) + endDay;
//Подсчет дней между годами
int whalDays = calculateDaysInYears(initialYear, endYear);
//Подсчет конечной цыфры
int allDay = whalDays + daysToTheEndOfEndYear + daysToTheEndOfStartYear;
//Вывод в консоль
std::cout << allDay;
}
else
{
//Дни месяцев между начальным и конечным месяцами
int daysInMonths = calculateMonth(initialMonth, endMonth, initialYear);
//Подсчет дней до конца начального месяца
int daysInFirstMonth = calculateAmountOfDays(initialDay, initialMonth, initialYear);
//Подсчет конечной цыфры
int allDay = daysInMonths + daysInFirstMonth + endDay;
//Вывод в консоль
std::cout << allDay;
}
return 0;
}
You should look at the DateTime class.
Also the msdn reference for C++ syntax.