C 語言程式檢查日期是否有效


給定日期格式為整數形式的日期、月份和年份。任務是確定日期是否可能。

有效日期範圍為 1800 年 1 月 1 日至 9999 年 12 月 31 日,超出此範圍的日期無效。

這些日期不僅包含年份範圍,還包含與日曆日期相關的所有約束條件。

約束條件為:

  • 日期不能小於 1 且大於 31
  • 月份不能小於 1 且大於 12
  • 年份不能小於 1800 且大於 9999
  • 當月份為 4 月、6 月、9 月、11 月時,日期不能超過 30。
  • 當月份為 2 月時,我們必須檢查:
    • 如果年份為閏年,則天數不能超過 29
    • 否則,天數不能超過 28。

如果所有約束條件都為真,則它是一個有效日期,否則不是。

示例

Input: y = 2002
   d = 29
   m = 11
Output: Date is valid
Input: y = 2001
   d = 29
   m = 2
Output: Date is not valid

演算法

START
In function int isleap(int y)
   Step 1-> If (y % 4 == 0) && (y % 100 != 0) && (y % 400 == 0) then,
      Return 1
   Step 2-> Else
      Return 0
In function int datevalid(int d, int m, int y)
   Step 1-> If y < min_yr || y > max_yr then,
      Return 0
   Step 2-> If m < 1 || m > 12 then,
      Return 0
   Step 3-> If d < 1 || d > 31 then,
      Return 0
   Step 4-> If m == 2 then,
      If isleap(y) then,
         If d <= 29 then,
            Return 1
         Else
            Return 0
         End if
      End if
   Step 5-> If m == 4 || m == 6 || m == 9 || m == 11 then,
      If(d <= 30)
         Return 1
      Else
         Return 0
         Return 1
      End Function
In main(int argc, char const *argv[])
   Step 1->Assign and initialize values as y = 2002, d = 29, m = 11
   Step 2-> If datevalid(d, m, y) then,
      Print "Date is valid"
   Step 3-> Else
      Print "date is not valid”
   End main
STOP

示例

 現場演示

#include <stdio.h>
#define max_yr 9999
#define min_yr 1800
//to check the year is leap or not
//if the year is a leap year return 1
int isleap(int y) {
   if((y % 4 == 0) && (y % 100 != 0) && (y % 400 == 0))
      return 1;
   else
      return 0;
}
//Function to check the date is valid or not
int datevalid(int d, int m, int y) {
   if(y < min_yr || y > max_yr)
      return 0;
   if(m < 1 || m > 12)
      return 0;
   if(d < 1 || d > 31)
      return 0;
      //Now we will check date according to month
   if( m == 2 ) {
      if(isleap(y)) {
         if(d <= 29)
            return 1;
         else
            return 0;
         }
      }
      //April, June, September and November are with 30 days
      if ( m == 4 || m == 6 || m == 9 || m == 11 )
         if(d <= 30)
            return 1;
         else
            return 0;
            return 1;
   }
int main(int argc, char const *argv[]) {
   int y = 2002;
   int d = 29;
   int m = 11;
      if(datevalid(d, m, y))
         printf("Date is valid
");       else          printf("date is not valid
");       return 0; }

輸出

如果執行上述程式碼,它將生成以下輸出:

Date is valid

更新於: 2019 年 10 月 18 日

3K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.