使用c语言编程时输入具体的年份和月份,求月份的天数的两种编程方法

方法一:使用if……else语句 

#include"stdio.h"
#include"conio.h"
int main()
{
	int year,month,days;

	printf("请依次输入整数的某年某月:");

	scanf("%d%d",&year,&month);

	if(month>12||month<1)                       //判断输入的月份数据是否正确

	printf("输入的月份数据错误\n");

	else
	{

	if((year%4==0&&year%100!=0)||(year%400==0)) //闰年的判断

	{
		if(month==2)
			days = 29;

		else if(month==4||month==6||month==9||month==11)

			days = 30;
		
		else

			days = 31;

		}

	else

	{
	
		if(month==2)

			days = 28;

		else if(month==4||month==6||month==9||month==11)

			days = 30;
		
		else

			days = 31;

		}
	
	}

	printf("the month of this year has these days: %d\n",days);

	getch();

	return 0;
}

方法二:使用switch语句

#include"stdio.h"
#include"conio.h"
int runnian(int year);//自定义求润年函数

void main()

{

	int year,month,days;

	printf("请依次输入整数的某年某月:");

	scanf("%d%d",&year,&month);

	if(month>12||month<1)

	printf("输入的月份数据错误\n");

	else
	{

	int days = 31;
	switch(month)
	{
		case 4:
		case 6:
		case 9:
		case 11:
		{
			days = 30;
			break;
		}

		case 2:

		{
			if(runnian(year))

				days = 29;
			else

				days = 28;

			break;

		}
	}

	printf("该年该月有: %d 天\n",days);

	}

	getch();

}

int runnian(int year)//自定义求闰年函数

{
	if((year%4==0&&year%100!=0)||(year%400==0))//符合闰年的条件
	{
	
	return 1;

	}

	return 0;
	}



你可能感兴趣的:(c++,c语言,算法)