C language programming every day (use of structure): what day is it in a year?

Define a structure to store the date (including year, month, day). And design a function to calculate the date stored in the incoming structure is the day of the year

Note:
1. Consider illegal dates, such as "April is small", then there cannot be 31st

2. Consider whether it is a leap year

code show as below

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

struct date
{
    short year;
    char month;
    char day;
};

bool isValid(int year, int month, int day)
{
    if(year<0 || month<1 || month>12 || day<1 || day>31)
        return false;
    
    if(month == 4 || month == 6 || month == 9 || month == 11)
    {
        if(day > 30)
            return false;
    }
    else if(month == 2)
    {
        if((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
        {
            if(day > 29)
                return false;
        }
        else
        {
            if(day > 28)
                return false;
        }
    }
    else
    {
        if(day > 31)
                return false;
    }
    
    return true;
}

int main(void)
{
    printf("请输入年月日(格式:1969/09/23) :");

    struct date sunny;
    scanf("%hd/%hhd/%hhd", &sunny.year,
                           &sunny.month,
                           &sunny.day);

    // 判定日期的合法性
    if(!isValid(sunny.year, sunny.month, sunny.day))
    {
        fprintf(stderr, "日期非法\n");
        exit(0);
    }


    int days[12] = {31, 0, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};//每月的最大天数,特殊的二月另外赋值即可
    int i, total_days = 0;

    // 判断是否闰年
    if((sunny.year%4==0 && sunny.year%100!=0) ||
       (sunny.year%400==0))
        days[1] = 29;
    else
        days[1] = 28;

    for(i=0; i<sunny.month-1; i++)
        total_days += days[i];
    total_days += sunny.day;

    printf("该日期是第%d天\n", total_days);

    return 0;
}

Guess you like

Origin blog.csdn.net/weixin_69884785/article/details/131970084