[C语言]求某年某月的天数(两个方法)

一道初阶c的题目

题目要求:写代码求出某年某月的天数
比如:输入 2022 11
输出 31

只需注意一点:当求2月时分情况讨论是否为闰年(闰年与平年2月份天数不一样),其他月份都不需要分别讨论

法一(switch语句)

#include <stdio.h>
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 <stdio.h>

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是一种文件结束标志,在头文件stdio.h中被宏定义为-1,由于ASCII范围0~127,当scanf的值不等于EOF证明scanf过程未出问题

此时进入循环,下标m即对应月份,同样在二月进行讨论即可

  • 7
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值