一道初阶c的题目
题目要求:写代码求出某年某月的天数
比如:输入 2022 11
输出 31
只需注意一点:当求2月时分情况讨论是否为闰年(闰年与平年2月份天数不一样),其他月份都不需要分别讨论
法一(switch语句)
#include <>
int main()
{
int year, month, days;
printf("input the year and the month\n");
scanf("%d %d", &year, &month);
switch (month)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
printf("It has 31 days\n");
break;
case 4:
case 6:
case 9:
case 11:
printf("It has 30 days\n");
break;
case 2:
if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0)
printf("It has 29 days\n");
else
printf("It has 28 days\n");
break;
}
return 0;
}
这个方法算是非常常规的做法,注意在case2的时候判断是否为闰年即可
闰年的条件是可以被4整除且不能被一百整除,但可以被400整除
法二
#include <>
int main()
{
int y, m;
int days[13] = { 0,31,28,31,30,31,30,31,31,30,31,30,31 };//下标表示月份
while (scanf("%d %d", &y, &m) != EOF);
{
int day = days[m];
if (m = 2)
{
if (y % 4 == 0 && y % 100 != 0 || y % 400 == 0)
day += 1;
}
printf("%d", day);
}
return 0;
}
这第二种方法通过创建数组days存储每个月份的天数
注意数组第一位为0是为了让数组的下标对应月份,另外EOF是一种文件结束标志,在头文件中被宏定义为-1,由于ASCII范围0~127,当scanf的值不等于EOF证明scanf过程未出问题
此时进入循环,下标m即对应月份,同样在二月进行讨论即可