C语言输入某年某月某日判断为当年的第几天(switch实例)

代码如下:

#include 
int main()
{
	int year, month, day, leap, sum;
	printf("请输入:");
	scanf("%d,%d,%d", &year, &month, &day);
	switch (month)
	{
	case 1:sum = 0;break;
	case 2:sum = 31;break;
	case 3:sum = 59;break;/*一月31天加平年28天等于59天*/
	case 4:sum = 90;break;
	case 5:sum = 120;break;
	case 6:sum = 151;break;
	case 7:sum = 181;break;
	case 8:sum = 212;break;
	case 9:sum = 243;break;
	case 10:sum = 273;break;
	case 11:sum = 304;break;
	case 12:sum = 331;break;
	default:printf("error\n");
	}
	sum = sum + day;
	if (year%400 == 0 || year%4 == 0 && year%100 != 0)/*判断闰年*/
		leap = 1;
	else
		leap = 0;
	if(leap == 1 && month>2)/*当是闰年,月份大于二时,才需要加一,为一月时,不需要加一*/
		sum = sum++;
	printf("为今年的%d\n",sum);
	return 0;
}

第二种方法:

#include 
int main()
{
	int year, month, day, sum=0;
	scanf("%d%d%d", &year, &month, &day);
	switch (month-1)
	{
	case 11:sum = sum + 30;
	case 10:sum = sum + 31;
	case 9:sum = sum + 30;
	case 8:sum = sum + 31;
	case 7:sum = sum + 31;
	case 6:sum = sum + 30;
	case 5:sum = sum + 31;
	case 4:sum = sum + 30;
	case 3:sum = sum + 31;
	case 2:
		if (year%400 == 0 || year%4 == 0 && year%4 == 0)
			   sum = sum + 29;
		else
			sum = sum +28;
	case 1:sum = sum + 31;
	case 0:sum = sum + day;printf("今年的第%d天\n", sum);break;
	default:printf("error\n");
	}
	return 0;
}

你可能感兴趣的:(C语言,c语言)