今天的題目:編程實現統計某年某月的天數
例如: 輸入:2017.7
輸出:31天
先附上我自己想的方法,由于幾個功能放一起太繁瑣,于是我想把他們分為三個函數,分別來實現這個功能:
#include <stdio.h>void runnian(int* year, int* leap); //函數聲明
void print(int month); //函數聲明int main()
{int year, month, leap;scanf ("%d.%d", &year, &month);//輸入年月runnian(&year, &leap);//判斷是否是閏年if (2 != month) //判斷是否是 2 月,不是則正常輸出print(month); //分 30 天和 31 天輸出else //如果是 2 月{if(1 == leap) //閏年 29 天printf ("29天");else //非閏年 28 天printf ("28天");}return 0;
}void runnian(int* year, int* leap) //判斷是否是閏年
{if (0 == *year % 4) //判斷能否被4整除{if (0 == *year % 100) //判斷能否被100整除{if (0 == *year % 400) //判斷能否被400整除*leap = 1; // leap = 1 為閏年else *leap = 0; // leap = 0 不是閏年}else *leap = 1;}else *leap = 0;
}void print(int month) //根據月份輸出天數
{switch(month){case 1:case 3:case 5:case 7:case 8:case 10:case 12:printf ("31天");break;case 4:case 6:case 9:case 11:printf ("30天");break;default:printf ("不存在的");}}
但是后來看到一個簡單的方法,可以用‘與或’來代替‘ if ’語句(即判斷閏年的函數),這樣多行的代碼就可以縮略為一行代碼,整個函數就更清爽,附上代碼:
#include <stdio.h>int main()
{int year;int month;printf ("請輸入");scanf ("%d.%d", &year, &month); //利用scanf輸入吃掉輸入時的 '.' switch(month){case 1:case 3:case 5:case 7:case 8:case 10:case 12:printf ("31天");break;case 4:case 6:case 9:case 11:printf ("30天");break;case 2:if (0 == year%4 && 0 != year%100|| 0 == year%400)printf ("29天");elseprintf ("28天");break;default:printf ("不存在的");}return 0;
}