計算兩個日期之間相隔的天數
阿新 • • 發佈:2018-11-07
/******************************************************* 程式內容:計算從一個日期到另一個日期一共經歷的天數 *******************************************************/ #include<iostream> using namespace std; int isprime_Month[13]={0,31,29,31,30,31,30,31,31,30,31,30,31}; int notprime_Month[13]={0,31,28,31,30,31,30,31,31,30,31,30,31}; int isprime(int year){ return (((year%4==0)&&(year%100)!=0)||(year%400==0))?1:0; } int main(){ int pre_year,pre_month,pre_day,later_year,later_month,later_day; int sum=0; cout<<"Please enter a previous date:"; cin>>pre_year>>pre_month>>pre_day; cout<<"Please enter a later date:"; cin>>later_year>>later_month>>later_day; if(pre_year==later_year&&pre_month==later_month){ sum=later_day-pre_day; } else{ for(int i=pre_year+1;i<=later_year-1;i++){ if(isprime(i)) sum+=366; else sum+=365; } if(pre_year==later_year){ for(int i=pre_month+1;i<=later_month-1;i++){ if(isprime(pre_year)) sum+=isprime_Month[i]; else sum+=notprime_Month[i]; } } else{ for(int i=pre_month+1;i<=12;i++){ if(isprime(pre_year)) sum+=isprime_Month[i]; else sum+=notprime_Month[i]; } for(int i=1;i<=later_month-1;i++){ if(isprime(pre_year)) sum+=isprime_Month[i]; else sum+=notprime_Month[i]; } } if(isprime(pre_year)) sum+=(isprime_Month[pre_month]-pre_day); else sum+=(notprime_Month[pre_month]-pre_day); sum+=later_day; } cout<<"sum is "<<sum; return 0; }