C 判斷 —— switch語句(輸入的年份判斷是否為閏年,根據輸入的月份判斷這月有多少天)
阿新 • • 發佈:2018-12-18
使用 switch 語句程式設計,根據輸入的年份判斷是否為閏年,根據輸入的月份判斷這月有多少天。
#include<stdio.h> int main() { int year, month, ex; printf("請輸入年份及月份(空格分隔):"); scanf("%d %d", &year, &month); if(month < 1 || month > 12) { printf("輸入有誤!!"); } else { if((year%4 == 0 && year%100 != 0) || year%400 == 0) { ex = 1; printf("%d年為閏年。\n", year); } else { ex = 0; printf("%d年不為閏年。\n", year); } switch(month) { case 4: case 6: case 9: case 11: printf("%d月有%d天。\n", month, 30); break; case 2: printf("%d月有%d天。\n", month, 28+ex); break; default: printf("%d月有%d天。\n", month, 31); } } }
測試結果顯示如下:
[[email protected] Test_20180418]# gcc switchUse.c
[[email protected] Test_20180418]# ./a.out
請輸入年份及月份(空格分隔):2018 10
2018年不為閏年。
10月有31天。