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
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP