C语言定义一个结构体变量(包括年,月,日).计算该日在本年中是第几天,注意闰年问题.
作者:野牛程序员:2024-01-03 21:36:54C语言阅读 2627
C语言定义一个结构体变量(包括年,月,日).计算该日在本年中是第几天,注意闰年问题.
#include <stdio.h> struct Date { int year; int month; int day; }; // 判断是否为闰年 int isLeapYear(int year) { if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) { return 1; // 闰年 } else { return 0; // 非闰年 } } // 计算某日期在本年中是第几天 int dayOfYear(struct Date date) { int daysInMonth[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; int dayCount = 0; // 累加前面月份的天数 for (int i = 1; i < date.month; ++i) { dayCount += daysInMonth[i]; } // 加上当前月份的天数 dayCount += date.day; // 对闰年进行处理,如果当前月份在二月之后,且为闰年,则再加一天 if (isLeapYear(date.year) && date.month > 2) { dayCount += 1; } return dayCount; } int main() { struct Date inputDate; // 用户输入日期 printf("输入年份: "); scanf("%d", &inputDate.year); printf("输入月份: "); scanf("%d", &inputDate.month); printf("输入日期: "); scanf("%d", &inputDate.day); // 计算并显示在本年中是第几天 int dayCount = dayOfYear(inputDate); printf("在本年中是第%d天\\n", dayCount); return 0; }
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892
