creating a duration calculation program

Moderators: Darobat, RecursiveS, Dante Shamest, Bugdude, Wizard

creating a duration calculation program

hi i study c++ at school. we have to do a project in hotel management so i tried to make a program to find no. of days between 2 dates
but whenever the dates are like x/12/2012 and y/3/2013 ie crossing to the next year the ntvdm error occurs
can you please tell me if theres something wrong with the code or my computer
(PSin school we learn c++ on turbo c++ (not the really old one)so to put it in my computer i had to use a virtual PC

#include<iostream.h>
struct date
{
int dd,mm,yy;
};
void Duration(date d1,date d2)
{
int days,m;
if(d2.mm-d1.mm==0)
{
days=d2.dd-d1.dd;
}
else
if(d2.mm-d1.mm!=0)
{
if(d1.mm==5||d1.mm==6||d1.mm==9||d1.mm==11)
days=30-d1.dd;
else
if(d1.mm==2)
days=28-d1.dd;
else
days=31-d1.dd;
m=d1.mm+1;
while(m!=d2.mm)
{
if(m==5||m==6||m==9||m==11)
days=days+30;
else
if(m==2)
days=days+28;
else
days=days+31;
m++;
}
days=days+d2.dd;
}
days++;//to include the last day
cout<<"days:"<<days;
}
void main()
{
date d1,d2;
cout<<"arrival:";
cin>>d1.dd>>d1.mm>>d1.yy;
cout<<"departure";
cin>>d2.dd>>d2.mm>>d2.yy;
Duration(d1,d2);
}
bryanpr

Posts: 1
Joined: Thu Jun 28, 2012 8:13 am

Re: creating a duration calculation program

If this code compiles you compiler definitely is old. I don't know why teachers always use out of date compilers.

Before you compare the months you should compare the years. Like the months you can count up the years until you reach the year and month you want. Make sure the month goes back to 1 at the end of a year.
Code: Select all
void Duration(date d1,date d2)
{
int days,m,y;
if(d2.mm-d1.mm==0 && d1.yy-d2.yy==0) // same year and month
{
days=d2.dd-d1.dd;
}
else // no if needed here
{
if(d1.mm==5||d1.mm==6||d1.mm==9||d1.mm==11)
days=30-d1.dd;
else if(d1.mm==2)
days=28-d1.dd;
else
days=31-d1.dd;
m=d1.mm+1;
y=d1.yy;
while(m!=d2.mm || y!=d2.yy)
{
if(m==5||m==6||m==9||m==11)
days=days+30;
else if(m==2)
days=days+28;
else
days=days+31;
m++;
if(m==13)
{
//go to january of next year
m=1;
y++;
}
}
days=days+d2.dd;
}
days++;//to include the last day
cout<<"days:"<<days;
}
And you should add a check if the given dates are valid and the second date is actually after the first. Like your code does now, if the second date is before the first, you will loop endless.
Who needs a signature anyway.

exomo

Posts: 879
Joined: Fri Sep 26, 2003 12:30 pm