这个代码逻辑应该算比较好懂的,但是比较繁琐...(如果懒得看,可以滑到下面那个代码,更加简洁)
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
//该日是本年中的第几天
struct Date
{
int year;
int month;
int day;
};
int main()
{
printf("请输入年月日:");
struct Date d;
int date2;
scanf("%d %d %d", &d.year, &d.month, &d.day);
if ((d.year% 4 == 0 && d.year%100 != 0) || d.year % 400 == 0)
{
printf("该年为闰年");
if (d.month == 2)//2月
{
date2 = 31 + d.day;
}
else if (d.month == 1)//1月
{
date2 = d.day;
}
else if (d.month == 3 || d.month == 5 || d.month == 7 || d.month == 8 || d.month == 10 || d.month == 12)//大月
{
if (d.month <= 7)
{
int i = (d.month - 1) / 2;//31的个数
date2 = i * 31 + 29 + 30 * (i - 1) + d.day;
}
else//大于8月
{
int i = d.month / 2;//31的个数
date2 = 29 + i * 31 + (i - 2) * 30 + d.day;
}
}
else if (d.month == 4 || d.month == 6 || d.month == 9 || d.month == 11)//小月
{
if (d.month <= 6)//小于6的30天
{
int i = d.month / 2;//31
date2 = 29 + i * 31 + (i - 2) * 30 + d.day;
}
else
{
int i = (d.month + 1) / 2;//31的个数
date2 = 29 + 31 * i + (i - 3) * 30 + d.day;
}
}
else
printf("输入错误");
printf("%d年%d月%d日是这年的第%d天", d.year, d.month, d.day);
}
else//平年
{
if (d.month == 2)//2月
{
date2 = 31 + d.day;
}
else if (d.month == 1)//1月
{
date2 = d.day;
}
else if (d.month == 3 || d.month == 5 || d.month == 7 || d.month == 8 || d.month == 10 || d.month == 12)//大月
{
if (d.month <= 7)
{
int i = (d.month - 1) / 2;//31的个数
date2 = i * 31 + 28 + 30 * (i - 1) + d.day;
}
else//大于8月
{
int i = d.month / 2;//31的个数
date2 = 28 + i * 31 + (i - 2) * 30 + d.day;
}
}
else if (d.month == 4 || d.month == 6 || d.month == 9 || d.month == 11)//小月
{
if (d.month <= 6)//小于6的30天
{
int i = d.month / 2;//31
date2 = 28 + i * 31 + (i - 2) * 30 + d.day;
}
else
{
int i = (d.month + 1) / 2;//31的个数
date2 = 28 + 31 * i + (i - 3) * 30 + d.day;
}
}
else
printf("输入错误");
}
printf("%d年%d月%d日是这年的第%d天", d.year, d.month, d.day,date2);
return 0;
}
用数组和函数优化以上代码:
看到这里的话,可以给我点个赞吗,谢谢你!😊欢迎大家评论区一起讨论o(* ̄▽ ̄*)ブ
#include <stdio.h>
// 该日是本年中的第几天
struct Date
{
int year;
int month;
int day;
};
// 函数声明,计算一年中的第几天
int dayOfYear(struct Date d);
int main()
{
printf("请输入年月日:");
struct Date d;
scanf("%d %d %d", &d.year, &d.month, &d.day);
int date2 = dayOfYear(d);
printf("%d年%d月%d日是这年的第%d天\n", d.year, d.month, d.day, date2);
return 0;
}
int dayOfYear(struct Date d)
{
int daysInMonth[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
int date2 = 0;
// 判断是否为闰年
if ((d.year % 4 == 0 && d.year % 100 != 0) || d.year % 400 == 0) {
daysInMonth[1] = 29; // 闰年2月有29天
printf("该年为闰年\n");
}
// 累加前面月份的天数
for (int i = 0; i < d.month - 1; i++) {
date2 += daysInMonth[i];
}
// 加上当前月的天数
date2 += d.day;
return date2;
}