[每天例题]计算日期到天数转换

发布时间 2023-04-07 14:49:34作者: 山远尽成云

计算日期到天数转换

题目

 

 题目要求

根据输入的日期,计算是这一年的第几天。

保证年份为4位数且日期合法。

思路分析

判断闰年方法:

1.年份可以被4整除,不能被100整除。

2.年份可以被400整除。

方法一(for if配套)

1.使用for循环不断将month前month天数相加,等到了month则直接加day。

2.在二月时区分闰年。闰年二月天数29,非闰年二月天数28。

代码

#include<stdio.h>
int main()
{
	int year,month,day,i,allday=0;
	scanf("%d %d %d",&year,&month,&day);
	for(i=1;i<month;i++) 
	{
		if((i==1)||(i==3)||(i==5)||(i==7)||(i==8)||(i==10)||(i==12))
		{
			allday+=31;
		}
		else if((i==4)||(i==6)||(i==9)||(i==11))
		{
			allday+=30;
		}
		else if(i==2)
		{
			if((year%4==0&&year%100!=0)||(year%400==0))
			{
				allday+=29;
			}
			else
			{
				allday+=28;
			}
		}
	}
	allday+=day;
	printf("%d",allday);
	return 0;
}

  方法二(switch语句)

1格式为:

switch(月份)

{

case(月份)

.

.

.

}

代码

#include<stdio.h>
int main()
{
    int year,month,day;
    int allday=0;
    scanf("%d %d %d",&year,&month,&day);
    switch(month)
    {
        case 12:
            allday+=30;//11月的天数 
        case 11:
            allday+=31;//10月的天数 
        case 10:
            allday+=30;//9月的天数
        case 9:
            allday+=31;//8月的天数
        case 8:
            allday+=31;//7月的天数
        case 7:
            allday+=30;//6月的天数
        case 6:
            allday+=31;//5月的天数
        case 5:
            allday+=30;//4月的天数
        case 4:
            allday+=31;//3月的天数
        case 3://2月的天数
            if((year%4==0&&year%100!=0)||(year%400==0)) 
            {
                allday+=29;
            }
            else
            {
                allday+=28;
            }
        case 2:
            allday+=31;//1月的天数
        case 1:
            break; 
    }
    allday+=day;
    printf("%d",allday);
    return 0;
}

运行结果