使用两个结构体变量,分别存放用户输入的两个介于2015.1.1至2020.12.31之间日期(包括年、月、日),然后计算两日期之间相隔多少天。

//1.使用两个结构体变量,分别存放用户输入的两个介于2015.1.1至2020.12.31之间日期(包括年、月、日),然后计算两日期之间相隔多少天。
#define _CRT_SECURE_NO_WARNINGS
#include"stdio.h"
struct date{
	int year;
	int month;
	int day;
}day[2];
int main(){
	int i,j,leap[2],yearday1,yearday2,yearday3=0,k;
	int  month_tab[2][13] = { 
   {0,31,28,31,30,31,30,31,31,30,31,30,31},
   {0,31,29,31,30,31,30,31,31,30,31,30,31}
	};
	for(j=0;j<2;j++){
		do{
			printf("请输入第%d个介于2015至2020之间的年:\n",j+1);
			scanf("%d",&day[j].year);
		}while(day[j].year>2020||day[j].year<2015);
		leap[j]=((day[j].year%4==0)&&(day[j].year%100!=0)||(day[j].year%400==0));
		do{ 
			printf("请输入第%d个介于1至12之间的月:\n",j+1);
			scanf("%d",&day[j].month); 			//输入月
		}while(day[j].month<1 || day[j].month>12);
		if(day[j].month==1 ||day[j].month==3 || day[j].month==5 || day[j].month==7 || day[j].month==8 ||day[j]. month ==10 ||day[j]. month==12)
			do{ 
				printf("请输入第%d个介于1-31之间的日:\n",j+1);
				scanf("%d",&day[j].day);			//输入日
			}while(day[j].day<1 || day[j].day>31); 
		else if(day[j].month==4 || day[j].month==6 || day[j].month==9 || day[j].month==11)
			do{ 	
				printf("请输入第%d个介于1-30之间的日:\n",j+1);
				scanf("%d",&day[j].day);			//输入
			}while(day[j].day<1 || day[j].day>30);
		else{
			if(leap[j]==0)
				do{ 
					printf("请输入第%d个介于1-28之间的日:\n",j+1);
					scanf("%d",&day[j].day);				//输入日
				}while(day[j].day<1 || day[j].day>28);
			else 
				do{ 
					printf("请输入第%d个介于1-29之间的日:\n",j+1);
					scanf("%d",&day[j].day);				//输入日
				}while(day[j].day<1 || day[j].day>29);
		}
	}
	if(day[0].year>day[1].year||day[0].month>day[1].month||day[0].day>day[1].day){
		int temp1,temp2,temp3;
		temp1=day[0].year;temp2=day[0].month;temp3=day[0].day;
		day[0].year=day[1].year;day[0].month=day[1].month;day[0].day=day[1].day;
		day[1].year=temp1;day[1].month=temp2;day[1].day=temp3;
	}
	k=day[1].year-day[0].year;
	if(k>1){
		for(i=1;i<k;i++){
			if(((day[0].year+i)%4==0)&&((day[j].year+i)%100!=0))
				yearday3=yearday3+366;
			else
				yearday3=yearday3+365;
		}
	}
	yearday1 = day[0].day ;
	for (i=1;i<day[0].month;i++)
		yearday1+=month_tab[leap[0]][i];	//计算是该年的第几天
	yearday2 = day[1].day ;
	for (i=1;i<day[1].month;i++)
			yearday2+=month_tab[leap[1]][i];
	if(k==0)
		printf("两日期相隔天数为%d\n",yearday2-yearday1);
	else{
		if(leap[0]==0)
			yearday1=365-yearday1;
		else
			yearday1=366-yearday1;
		printf("两日期相隔天数为%d\n",yearday1+yearday2+yearday3);
	}
	return 0;
}

你可能感兴趣的:(c语言)