欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

c语言 输出一个日期是该年的第几天

程序员文章站 2022-05-23 09:18:34
...

这个版本逻辑相对清晰,错误输入的判断十分完整;

#include <stdio.h>
/*******tonytrek 2021.7.17**********/
//input date,out put the count of the day from the begain of that year
int data_cal(int,int,int);
int main()
{
    int year=2012,month=2,date=29;
    int ret=data_cal(year,month,date);
    printf("ret=%d\n",ret);
    return 0;
}
int data_cal(int year,int month,int date)
{
int data_list[12]={31,28,31,30,31,30,31,31,30,31,30,31};
int iter,cal;
if(0==year%400||(0!=year%100&&0==year%4)) //first level data exception
    data_list[1]+=1;
if(year<1000||year>4000||month>12||month<0||date<0) //second level data exception
{
    printf("bad inpute date\n");
    return -1;
}
if(date>data_list[month-1])
{
    printf("bad data\n");
    return -1;
}
for(iter=0;iter<month-1;iter++)
{
    cal+=data_list[iter];
}
cal+=date;
return cal;
}