利用函数我们计算某年某月有多少天?

我们计算某年某月有多少天?

设计函数get_days_of_month,来完成

       1   2   3   4   5   6   7   8   9   10  11   12
     31   28  31  30  31  30  31  31  30  31  30   31 
          29

闰年的判断
1. 能被4整除,并且不能被100整除,是闰年
2. 能被400整除是闰年
是闰年返回1,不是闰年返回0

//方法一
int is_leap_year(int y)
{
	if (((y % 4 == 0) && (y % 100 != 0)) || (y % 400 == 0))
		return 1;
	else
		return 0;
}

int get_days_of_month(int y, int m)
{
	int days[] = { 0, 31,28,31,30,31,30,31,31,30,31,30,31 };
	             //0  1  2  3  4 ...
	int day = days[m];

	if (is_leap_year(y) && m == 2)
		day += 1;
	  return day;
}

int main()
{
	int year = 0;
	int month = 0;
	scanf("%d %d", &year, &month);//2024 1
	
	int day = get_days_of_month(year, month);
	
	printf("%d\n", day);

	return 0;
}

//方法二
int is_leap_year(int y)
{
	if (((y % 4 == 0) && (y % 100 != 0)) || (y % 400 == 0))
		return 1;
	else
		return 0;
}

int get_days_of_month(int y, int m)
{
	//int days[] = { 0, 31,28,31,30,31,30,31,31,30,31,30,31 };
	//0  1  2  3  4 ...
	int day = 0;
	switch (m)
	{
	case 2:
		day = 28;
		break;
	case 1:
	case 3:
	case 5:
	case 7:
	case 8:
	case 10:
	case 12:
		day = 31;
		break;
	case 4:
	case 6:
	case 9:
	case 11:
		day = 30;
	}

	if (is_leap_year(y) && m == 2)
		day += 1;

	return day;
}

int main()
{
	int year = 0;
	int month = 0;
	scanf("%d %d", &year, &month);//2024 1

	int day = get_days_of_month(year, month);

	printf("%d\n", day);

	return 0;
}

你可能感兴趣的:(我的C语言--常见的题型,c语言)