回复 19楼 TonyDeng
我试试
回复 20楼 a249426519
我觉得你就没看明白他的话的意思。你们俩目前就不在一个境界里面。另外你有点矫情我觉得。
#include<stdio.h> #include<time.h> #include<ctype.h> #define YEAR_MAX 10000000 int isLeap(int year) { return !(year % 4) && year % 100 || !(year % 400); } int days(int year, int month, int day) { const int predays[] = {0, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 }; return predays[month] + day + (month > 2 ? isLeap(year) : 0); } int formatDate(char *str, int *year, int *month, int *day) { const int md[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; char *p; for(p = str; isdigit(*p) || *p == '-' && p != str && p[1] && p[1] != '-'; p++); if(*p && *p != '\n') return 0; *p = 0; for(*year = 0; isdigit(*str) && *year <= YEAR_MAX; *year = *year * 10 + *(str++) - '0'); if(*year == 0 || *year > YEAR_MAX || !*(str++)) return 1; for(*month = 0; isdigit(*str) && *month <= 12; *month = *month * 10 + *(str++) - '0'); if(*month == 0 || *month > 12 || !*(str++)) return 1; for(*day = 0; isdigit(*str) && *day <= 31; *day = *day * 10 + *(str++) - '0'); if(*day == 0 || *day > md[*month] + ((*month == 2) ? isLeap(*year) : 0)) return 1; return 2; } int main() { int year, month, day; char str[32]; struct tm * date; time_t now; time(&now); date = localtime(&now); printf("输入待计算日期(格式为%d-%d-%d): ", date->tm_year + 1900, date->tm_mon + 1, date->tm_mday); fgets(str, 128, stdin); switch(formatDate(str, &year, &month, &day)) { case 0: printf("\n输入格式错误\n"); break; case 1: printf("\n无效日期\n"); break; case 2: printf("\n%d-%d-%d为%d年第%d天\n", year, month, day, year, days(year, month, day)); } return 0; }