呵呵 帮优化优化阿 呵呵 谢谢啦
#include<stdio.h> int leap(int year) { if( (year%4==0&&year%100!=0)||(year%400==0) ) return 1; else return 0; } int leftdays1(int year1,int year2) { int a; int days=0; for(a=1;a<(year2-year1);a++) days+=(365+leap(year1+a) ); return days; } int leftdays2(int month,int year) { int sum=0; int i; int d[13]={0,31,28,31,30,31,30,31,31,30,31,30,31}; for(i=0;i<month;i++) sum+=d[month]; if( leap(year) && month>2 ) sum+=1; return sum; } main() { int b_year,b_month,b_day; int o_year,o_month,o_day; int totaldays; int a,b,c; int d[13]={0,31,28,31,30,31,30,31,31,30,31,30,31}; clrscr(); printf("please input the begin date with space\n"); scanf("%d %d %d",&b_year,&b_month,&b_day); printf("please input the end date\n"); scanf("%d %d %d",&o_year,&o_month,&o_day); a=leftdays1(b_year,o_year); b=leftdays2(o_month,o_year)+o_day; c=365+leap(b_year)-leftdays2(b_month+1,b_year); totaldays=a+b+c+d[b_month]-b_day; if(leap(b_year)&&b_month==2) totaldays+=1; printf("There are %d days left\n",totaldays); getch(); }
----------------解决方案--------------------------------------------------------
程序写得逻辑还是有点问题吧!不过没有看懂你的程序是要实现什么功能,能否说的更加清楚点!!
如果是计算,两个日期之间的天数的差别这个程序确实有问题!!比如输入2008 1 1和2008 1 2输出会多出来很多的!!
----------------解决方案--------------------------------------------------------
楼主,偶对你的程序很感兴趣,所以花时间修改了一下,改动比较多可别介意啊
//两个年月日之间相隔的天数
#include <stdio.h> #include <conio.h>
int leap(int year) { if( (year%4==0&&year%100!=0)||(year%400==0) ) return 1; else return 0; }
int leftdays1(int year,int month,int day) { int i; int days=0; int d[13]={0,31,28,31,30,31,30,31,31,30,31,30,31}; for(i=month+1;i<=12;i++) { if(i==2&&leap(year)==1) days+=29; else days+=d[i]; } days+=(d[month]-day); return days; }
int leftdays2(int year,int month,int day) { int i; int days=0; int d[13]={0,31,28,31,30,31,30,31,31,30,31,30,31}; for(i=1;i<month;i++) { if(month>=3&&i==2&&leap(year)==1) days+=29; else days+=d[i]; } days+=day; return days; }
int main() { int b_year,b_month,b_day; int o_year,o_month,o_day; int totaldays; int i,a,b,c=0,m=0; int d[13]={0,31,28,31,30,31,30,31,31,30,31,30,31}; clrscr(); printf("please input the start date with space\n"); scanf("%d %d %d",&b_year,&b_month,&b_day); printf("please input the end date\n"); scanf("%d %d %d",&o_year,&o_month,&o_day); a=leftdays1(b_year,b_month,b_day); b=leftdays2(o_year,o_month,o_day);
for(i=1;i<(o_year-b_year);i++) c+=365+leap(b_year+i);
if(o_year>b_year) totaldays=a+b+c; else if(o_year==b_year&&o_month>b_month) { for(i=1;i<(o_month-b_month);i++) { if(i==2) m+=d[i]+leap(b_year); else m+=d[i]; } totaldays=m+d[b_month]-b_day+o_day; } else totaldays=o_day-b_day; printf("There are %d days left\n",totaldays); getch(); return 0; }
算法是:
如果年份不等,则算出相隔年数的总天数和各自两个年份的零碎天数
如果年份相等,月份不等,则算出相隔月数的总天数和各自两个月份的零碎天数
如果月份相等 ,则天数相减为所得
[此贴子已经被作者于2004-11-23 12:21:34编辑过]
----------------解决方案--------------------------------------------------------