求一个程序,计算出生日到计算日的总天数的算法!!!
课后作业 谢谢啦!!!
用Java改的
#include <stdio.h>
#include <stdlib.h>
int year1,year2,month1,month2,day1,day2;
//判断是否是闰年
bool isLeapYear(int year){
return ((year % 400 == 0) || (year % 4 == 0 && year % 100 != 0));
}
//确保两个日期的先后顺序,日期一在日期二前
void check(){
if(year1 > year2 || (year1 == year2 && month1 > month2)
|| ( year1 == year2 && month1 == month2 && day1 > day2 ))
{
int tempYear = year1;
int tempMonth = month1;
int tempDay = day1;
year1 =year2;
month1 = month2;
day1 = day2;
year2 = tempYear;
month2 = tempMonth;
day2 = tempDay;
}
}
//返回某年某月的天数
int dayOfMonth(int year, int month){
if (month == 1 || month == 3 || month == 5 || month == 7
|| month == 8 || month == 10 || month == 12)
return 31;
else if(month == 4 || month == 6 || month == 9 || month == 11)
return 30;
else if(month == 2){
if (isLeapYear(year))
return 29;
else
return 28;
}
return 0;
}
//该日期与本年第一天的差
int days(int year, int month, int day){
int count = 0;
count += day;
month--;
while(month > 0){
count += dayOfMonth(year,month);
month--;
}
return count;
}
int main(void) {
int n = 0;
printf("请输入第一个日期:");
scanf("%d %d %d",&year1,&month1,&day1);
printf("请输入第二个日期:");
scanf("%d %d %d",&year2,&month2,&day2);
check();//确保两个日期的先后顺序,日期一在日期二前
n = 0;
n -= days(year1,month1,day1);
n += days(year2,month2,day2);
while(year1 < year2){
n += (isLeapYear(year1)?366:365);
year1++;
}
printf("日期之差为%d天",n);
system("pause");
}