C - 實驗課檢查日期是否合法

水貼一張。給老師代課時寫的代碼。來騙波訪問量。

根據輸入的年月日,來判斷是否合法。(代碼沒有判斷輸入的月份爲負數、大於12等等情況)。

主要思想:判斷是否爲閏年,確定2月的日期範圍。

                 根據月份,判斷日期的範圍。

#define _CRT_SECURE_NO_WARNINGS
#include "stdio.h"
#include "stdbool.h"
struct Date
{
	int year;
	int month;
	int day;
};
typedef struct Date Date;
int checkDate(Date date){
	int m = 0;
	bool m_year;
	m_year = ((date.year) % 4 == 0 && (date.year) % 100 != 0) || ((date.year) % 400 == 0); // 計算是否爲閏年

	switch (date.month){
	case 1:
	case 3:
	case 5:
	case 7:
	case 8:
	case 10:
	case 12: if (date.day > 31)  m = 1; break;
	case 2: if (m_year && (date.day > 29))
						m = 2;
			else if (!m_year && (date.day > 28))
						m = 4;
			break;
		
	default: if (date.day > 30)  m = 3; break;
	}

	return m;
}

int main(){
	Date date;
	int mark;
	scanf("%d%d%d", &date.year, &date.month, &date.day);
	mark = checkDate(date);
	switch (mark)
	{
	case 1:printf("error!!! %d 月最多隻有31天\n", date.month); break;
	case 2:printf("error!!! 閏月最多隻有29天\n"); break;
	case 4:printf("error!!! 平月最多隻有28天\n"); break;
	case 3:printf("error!!! %d月最多隻有30天\n", date.month); break;
	case 0: printf("right!!!"); break;
	}
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章