C语言小程序(二)、计算第二天日期
输入一个日期,判断下一个日期是哪一天,如果日期输入错误,则调用Linux下的cal命令显示输入的月份。
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> int year, month, day; const int day_30 = 30; const int day_31 = 31; int day_month_2 = 0; char err_flag = 0; void compute() { printf("输入年月日(1992-7-19):"); scanf("%d-%d-%d",&year, &month, &day); if((year%4==0 && year%100!=0) || (year%400==0)) { day_month_2 = 29; } else { day_month_2 = 28; } if(month>=1 && month<=12) { if(month == 2) { if(day > day_month_2) { err_flag = 1; } else if(day == day_month_2) { month++; day = 1; } else { day++; } } else if(month==1 || month==3 || month==5 || month==7 ||\ month==8 || month==10 || month==12) { if(day > day_31) { err_flag = 1; } else if(day == day_31) { month++; day = 1; } else { day++; } } else { if(day > day_30) { err_flag = 1; } else if(day == day_30) { month++; day = 1; } else { day++; } } if(month > 12) { year++; month = 1; } } else { err_flag = 1; } } int main() { time_t now; char ch, c; char call_cal[30]; do { compute(); if(err_flag) { err_flag = 0; printf("日期输入错误,调用cal命令查询%d年%d月:\n\n",year, month); sprintf(call_cal, "/usr/bin/cal %d %d",month, year); system(call_cal); //system("clear"); while((c=getchar())!='\n' && (c=getchar())!=EOF); printf("是否重新输入(y/n):"); } else { printf("第二天为%d-%d-%d。\n",year, month, day); while((c=getchar())!='\n' && (c=getchar())!=EOF); printf("是否再次输入日期(y/n):"); } ch = getchar(); } while(ch=='y' || ch=='Y' || ch=='\n'); time(&now); printf("Now is %s",ctime(&now)); puts("Having a goodday!"); return 0; }