C语言,输入年月日,判断是这一年的第几天?
以2月10日为例,应该先把前两个月的加起来,然后再加上5天即本年的第几天,特殊情况,闰年且输入月份大于3时需考虑多加一天。
源代码:
#include "stdio.h"
#include "stdlib.h"
int main()
{
int day,month,year,sum,leap;
printf("\nplease input year,month,day\n");
scanf("%d,%d,%d",&year,&month,&day);
switch(month) /*先计算某月以前月份的总天数*/
{
case 1:sum=0;break;
case 2:sum=31;break;
case 3:sum=59;break;
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=334;break;
default:printf("data error\n");break;
}
sum=sum+day; /*再加上某天的天数*/
if(year%400==0||(year%4==0&&year%100!=0)) /*判断是不是闰年*/
{
leap=1;
}
else
{
leap=0;
}
if(leap==1&&month>2) /*如果是闰年且月份大于2,总天数应该加一天*/
{
sum++;
}
printf("It is the %dth day.\n",sum);
return 0;
}
输出
please input year,month,day
2019,02,10
It is the 41th day.
扩展资料
c语言编写程序根据输入的时间分别输出问候语
#include <stdio.h>
int main()
{
int a;
printf("请输入时间,例如:17");
scanf("%d",&a);
if(a<=12&&a>=0) printf("早");
else if(a>12&&a<=14) printf("午");
else printf("晚");
printf("%d",s);
return 0;
1、先定义每个月的天数,2月按28天算输入年月日后,根据年判断是否闰年(闰年加1天),再从1月加到当月的前一月,再加上日期就可以了
2、例程:
#include <stdio.h>
int month[12] = {31,28,31,30,31,30,31,31,30,31,30,31};
main()
{
int yy,mm,dd, days;
int i;
printf("input year:"); scanf("%d", &yy);
printf("input month:"); scanf("%d", &mm);
printf("input day:"); scanf("%d", &dd);
/* 如果大于2月,要做闰年的判断,忘了,不一定准 */
if( mm > 2 && ((year%4==0 && year%100!=0) || year%400==0) ) days = 1;
else days = 0;
/* 加上前面各整月的天数 */
for(i = 0; i < mm-1; i++) days += month[i];
/* 加上日数 */
days += dd;
printf("This is the %d day of year %d!!\n", days, yy);
}
//输入:1999 2 1
//输出:This is the 32 day of year 1999!!
2019-07-31
int main()
{
int day,month,year,sum=0,leap;
printf("输入年月日如2019 7 12\n");
scanf("%d %d %d",&year,&month,&day);
switch(month)
{
case 1:sum=0;break;
case 2:sum=31;break;
case 3:sum=59;break;
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=334;break;
default:printf("data error");break;
}
sum=sum+day;
if((year%400==0||(year%4==0&&year%100!=0))&&month>2)
sum++;
printf("这是这一年的第%d天。",sum);
return 0;
}
方法2
#include<stdio.h>
int day_of_year(int (*p)[13],int year,int month,int day)
{
int i,leap;
leap=(year%100!=0 && year%4 ==0||year%400 ==0);
for(i=1;i<month;i++)
day+=*(*(p+leap)+i);
return day;
}
main()
{
static int day_tab[][13]={{0,31,28,31,30,31,30,31,31,30,31,30,31},{0,31,29,31,30,31,30,31,31,30,31,30,31}};
int a,b,c;
scanf("%d %d %d",&a,&b,&c);
printf("%d\n",day_of_year(day_tab,a,b,c));
}