萬盛學電腦網

 萬盛學電腦網 >> 網絡編程 >> 編程語言綜合 >> C語言小程序 計算第二天日期示例代碼

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月:nn",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;
}  
copyright © 萬盛學電腦網 all rights reserved