struct
{ int year
int month
int day
}date
int main()
{int days
cout<<"input year,month,day:"局液
char ch='\\'
cin>>date.year>>ch>>date.month>>ch>>date.day
switch(date.month)
{ case 1: days=date.day break
case 2: days=date.day+31 break
case 3: days=date.day+59 break
case 4: days=date.day+90 break
case 5: days=date.day+120 break
case 6: days=date.day+151 break
case 7: days=date.day+181 break
case 8: days=date.day+212 break
case 9: days=date.day+243 break
case 10: days=date.day+273break
case 11: days=date.day+304break
case 12: days=date.day+334break
}
if ((date.year %4== 0 &&date.year % 100 != 0
||date.year % 400 == 0) &&date.month >=3)
days+=1
cout<<date.month<<"/"<<date.day<桐简物<" is the "咐慧<<days
<<"th day in "<<date.year<<"."<<endl
return 0
}
1970 年以后的时间,可以用 time.h 里的函数计算。时间精度为秒。按题目要求,输出时间单位用天。程序如下:#include <stdio.h>
#include <time.h>
time_t YMD_hhmmss_2_s70(int Y, int M, int D, int hh, int mm, int ss){
struct tm *target_tm
time_t tt
time (&tt)
target_tm=localtime(&tt)
target_tm->tm_year = Y - 1900
target_tm->tm_mon= M - 1
target_tm->tm_mday = D
target_tm->tm_hour = hh // hour
target_tm->tm_min = mm
target_tm->tm_sec = ss
tt = mktime(target_tm) // from tm to time_t (s)
return tt
}
int main()
{
int y1,m1,d1,y2,m2,d2
time_t t1,t2
int dt
printf("input y1 m1 d1: ")
scanf("知并%d %d %d",&y1,&m1,&d1)
printf("\ninput y2 m2 d2: ")
scanf("%d %d %d",&y2,&m2,&d2)
t1 = YMD_hhmmss_2_s70(y1,m1,d1,0,0,0)
t2 = YMD_hhmmss_2_s70(y2,m2,d2,0,0,0)
dt = (t2-t1)/(24*3600)
printf("\ndt=%d\n",dt)
return 0
}
这里未包含日期的合法性判断。磨陵
1970 年以前 要另写程序。某年的日子是当年的第几天可用下面函数得出:
int YMD_2_JD(int Y, int M, int D){
const short MonthDay[]={0,31,28,31,30,31,30,31,31,30,31,30,31}
int JD,i
JD=D
for (i=0i<Mi++) JD+=MonthDay[i]
if (((Y%4==0)&&(Y%100!=0)||(Y%400==0)) &&(M>2)) JD++
return JD
}
某年是否闰年,用 (Y%4==0)&&(Y%100!=0)||(Y%400==0) 判断。闰年366天,平年365天。 有了这些,写程序不难。
未考虑公元前的年月日计算。
#include <stdio.h>
int main()
{
int year,month,day//年态滚月日
int judge,i
int sum=0//标记天数
int date[2][12]={
{31,28,31,30,31,30,31,31,30,31,30,31},
{31,29,31,30,31,30,31,31,30,31,30,31}}//储存闰年和非闰年每一月的天数
printf("输入年月日:")
scanf("%d %d %d",&year,&month,&day)
judge=(year%4==0)||(year%400==0 &&year%100!=0)
//判断年份是不是闰年帆喊余 是闰年judge就渗雀是1否则就是0
for(i=0i<month-1i++)//加month之前的所有天数
sum+=date[judge][i]
sum+=day//加当天月份的天数day
printf("它是%d年中的第%d天\n",year,sum)
return 0
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)