C语言:输入某年某月某日,判断这一天是这一年的第几天?(含结构体)

本文介绍了一种高效算法,用于判断输入特定年份和月份的日期是该年的第几天,包括闰年特殊情况的处理。通过两种编程实现方式,展示了如何计算并输出结果,适合初学者理解日期计算原理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:输入某年某月某日,判断这一天是这一年的第几天?
分析:以3月5日为例,应该先把前两个月的加起来,然后再加上5天即本年的第几天,特殊情况,闰年且输入月份大于3时需多加一天。

普通方法:

int main() {
	int year, month, day;
	printf("请输入年.月.日:");
	scanf("%d.%d.%d", &year, &month, &day);
	switch (month) {
    case 1:break; // 1月输入第几号,就是本年第几天
	case 2:day += 31;break; // 这里直接用day存储的天数
	case 3:day += 59;break;
    case 4:day += 90;break;
    case 5:day += 120;break;
    case 6:day += 151;break;
    case 7:day += 181;break;
    case 8:day += 212;break;
    case 9:day += 243;break;
    case 10:day += 273;break;
    case 11:day += 304;break;
    case 12:day += 334;break;
    default:printf("data error");break;
	}
    // 判断当年是否为闰年,若为闰年,3月以后的天数都加1
    if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
        if (month >= 3) {
            day++;
        }
    }
    printf("是%d年的第%d天\n", year, day);
	return 0;
}

结构体

int main() {
    struct Date {
        int year;
        int month;
        int day;
    }date;
    int total; // 记录总天数
    printf("请输入年.月.日:");
    scanf("%d.%d.%d", &date.year, &date.month, &date.day);
    switch (date.month) {
    case 1:break; // 1月输入第几号,就是本年第几天
    case 2:total = 31;break; // 2月时,暂时存储2月前的总天数,即一月的天数,以下同理
    case 3:total = 59;break;
    case 4:total = 90;break;
    case 5:total = 120;break;
    case 6:total = 151;break;
    case 7:total = 181;break;
    case 8:total = 212;break;
    case 9:total = 243;break;
    case 10:total = 273;break;
    case 11:total = 304;break;
    case 12:total = 334;break;
    default:printf("data error");break;
    }
    total += date.day;//total在加上当月的天数
    // 判断当年是否为闰年,若为闰年,3月以后的天数都加1
    if ((date.year % 4 == 0 && date.year % 100 != 0) || date.year % 400 == 0) {
        if (date.month >= 3) {
            total++;
        }
    }
    printf("%d.%d.%d是%d年的第%d天\n", date.year,date.month,date.day,date.year, total);
    return 0;
}

运行效果:
在这里插入图片描述

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

qinnt

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值