这道题小弟确实做不出来,请教高手一下!!
计算两个日期差值的程序
以下程序是我刚学完结构时写的,给你参考一下!
#include<iostream.h> struct data { int year,months,day; }; int leap_year(struct data *); int data_year(struct data *); int days_of_months(struct data*,int); int days_of_year(struct data *); int data_year(struct data *pd) { int days=0; for(int i=0;i<=(pd->months-1);i++) { days+=days_of_months(pd,i); } days+=pd->day; return days; } int days_of_year(struct data *pd) { if(leap_year(pd)==1) return 366; else return 365; } int days_of_months(struct data *pd,int p) { int days[12]={0,31,28,31,30,31,30,31,31,30,31,30}; if(leap_year(pd)==1&&p==2) return 29; else return days[p]; } int leap_year(struct data *pd) { int flag=0; if(((pd->year%4==0)&&(pd->year%100!=0))||pd->year%400==0) flag=1; return flag; } void main() { int a(0); while(a!=1) { struct data data1,data2; int days,years=0; cout<<"请输入开始日期 : "<<'\n'<<"年 :"; cin>>data1.year; cout<<"月 :"; cin>>data1.months; cout<<"日 :"; cin>>data1.day; cout<<'\n'<<"请输入结束日期 : "<<endl; cout<<"年 :"; cin>>data2.year; cout<<"月 :"; cin>>data2.months; cout<<"日 :"; cin>>data2.day; cout<<endl; if((data2.year-data1.year)==0) days=data_year(&data2)-data_year(&data1); else { days=data_year(&data2)+days_of_year(&data1)-data_year(&data1); int j=data2.year-data1.year-1; for(int i=1;i<=j;i++) { data1.year+=1; if(leap_year(&data1)==1) years+=366; else years+=365; } data1.year-=j; days+=years; } cout<<"从 "<<data1.year<<" 年 "<<data1.months<<" 月 "<<data1.day<<" 日到 "<<data2.year <<" 年 "<<data2.months<<" 月 "<<data2.day<<" 日相隔 "<<days<<" 天 "<<endl; cout<<'\n'<<"要继续使用软件请输入: 0 ."<<'\n'<<"要退出应用程序请输入: 1 ."<<endl; cout<<"请选择操作 : "; cin>>a; cout<<endl; } }
[此贴子已经被作者于2004-07-08 11:29:04编辑过]
#include<stdio.h>
int IsLeap(int year)
{
if(year%4==0&&year%100!=0||year%400==0)
return(1);
return(0);
}
int main()
{
int year1,month1,day1,year2,month2,day2;
long n=0;
printf("输入起始年份:");
scanf("%d%d%d",&year1,&month1,&day1);
printf("输入结束年份:");
scanf("%d%d%d",&year2,&month2,&day2);
while(year1<year2)
{
if(IsLeap(year1)==1)
{
n=n+366;
}
else
{
n=n+365;
}
year1++;
}
while(month1<month2)
{
switch(month1)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:n=n+31;break;
case 4:
case 6:
case 9:
case 11:n=n+30;break;
case 2:
{
if(IsLeap(year1)==1)
{
n=n+29;
}
else
{
n=n+28;
}
break;
}
}
month1++;
}
n=n+day2-day1;
printf("%ld\n",n);
return(0);
}