Skip to content

判断日期是否合法(含闰年判定)

Xu Pu edited this page Sep 28, 2015 · 1 revision

这里主要使用了三个技巧:

  • 数组
  • 逻辑表达式短路
  • 自定义函数,取巧的返回值
#include <stdio.h>

int is_leap_year(int year) {
    if ((year % 400 == 0) || (year % 4 == 0 && year % 100 != 0)) {
        return 1;
    } else {
        return 0;
    }
    // return (year % 400 == 0) || (year % 4 == 0 && year % 100 != 0) ? 1 : 0;
}

int main() {
    int days[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; // 月份从1开始,但数组是从0开始的
    
    int a , b , c;
    printf("输入一个日期,年月日之间用空格间隔:\n");
    scanf("%d %d %d", &a, &b, &c);
    days[2] = 28 + is_leap_year(a); // 对闰年的二月加一天
    if (b >= 1 && b <= 12 && c >= 1 && c <= days[b]) {
        printf("Yes");
    } else {
        printf("No");
    }
    return 0;
}
Clone this wiki locally