用C语言编写一个能判断输入的日期是否合法的小程序。如果合法,则按照年月日的输出此日期,比如1998年6月26日。;否则提示用户:您输入的日期有误,请重新输入!
时间: 2024-04-10 19:26:40 浏览: 20
下面是一个能够判断输入日期是否合法并输出的C语言程序示例:
```c
#include <stdio.h>
int isLeapYear(int year) {
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
return 1;
}
return 0;
}
int isValidDate(int year, int month, int day) {
if (year < 1 || month < 1 || month > 12 || day < 1) {
return 0;
}
int daysInMonth[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if (isLeapYear(year)) {
daysInMonth[1] = 29; // 闰年2月有29天
}
if (day > daysInMonth[month - 1]) {
return 0;
}
return 1;
}
int main() {
int year, month, day;
printf("请输入日期(年月日,以空格分隔):");
scanf("%d %d %d", &year, &month, &day);
if (isValidDate(year, month, day)) {
printf("您输入的日期为:%d年%d月%d日\n", year, month, day);
} else {
printf("您输入的日期有误,请重新输入!\n");
}
return 0;
}
```
该程序使用了两个函数:`isLeapYear`用于判断是否为闰年,`isValidDate`用于判断日期是否合法。在`isLeapYear`函数中,根据闰年的定义,如果年份能被4整除但不能被100整除,或者能被400整除,则是闰年,返回1;否则返回0。在`isValidDate`函数中,首先检查年、月、日是否合法(大于等于1),然后根据闰年的情况确定每个月的天数,最后判断输入的日期是否超出了对应月份的天数范围。
在`main`函数中,首先使用`scanf`函数获取用户输入的年、月、日,然后调用`isValidDate`函数判断日期是否合法。如果合法,则使用`printf`函数输出日期;否则输出提示信息。
希望这个示例对您有帮助!如有更多问题,请随时提问。