学无先后,达者为师

网站首页 编程语言 正文

用C语言根据天数输出对应的年、月、日

作者:Sunday王-YH 更新时间: 2022-07-22 编程语言

题目描述:输入年份和这一年的第几天,输出具体的年、月、日的信息。(注意闰年的判断!)

输入要求:输入两个整数分别代表年份和这一年的第几天。(假设数据都在有效范围内)

输出要求:输出对应的年、月、日。输出的数字之间以一条横线间隔,输出完毕换行。

代码如下:

#include<stdio.h>

//接口定义,year为年,date为天数,*nmonth是计算得出的月,*nday是计算得出的日
void month_day(int year, int date, int* nmonth, int* nday) {
    int yu, hao;
    int wang[2][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},                        //定义数组存放闰年和平年的天数
    };
    hao = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;        //闰年判别条件
    for (yu = 1; date > wang[hao][yu]; yu++)
        date -= wang[hao][yu];
    *nmonth = yu;
    *nday = date;
}
int main() {
    int day, month, year, date;                                //定义日、月、年和天数的变量
    printf("请输入年份和第几天:\n");
    scanf_s("%d%d", &year, &date);
    if (date >= 1 && year >= 1) {
        if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0 && date < 367) {
            month_day(year, date, &month, &day);
            printf("具体年、月、日如下:\n%d-%d-%d", year, month, day);
        }
        if (year % 4 != 0 && date < 366) {
            month_day(year, date, &month, &day);
            printf("具体年、月、日如下:\n%d-%d-%d", year, month, day);
        }
    }
    else {
        printf("搞事情是吧?这边给你强行退出!\n");
    }
    return 0;
}

原文链接:https://blog.csdn.net/weixin_67793168/article/details/125919329

栏目分类
最近更新