C Program to Calculate Day of Year from Date
#include <stdio.h>
int isLeapYear(int year) { if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) return 1; return 0; }
int calculateDayOfYear(int year, int month, int day) { int daysInMonth[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
if (isLeapYear(year))
daysInMonth[1] = 29;
int dayOfYear = 0;
for (int i = 0; i < month - 1; i++)
dayOfYear += daysInMonth[i];
dayOfYear += day;
return dayOfYear;
}
int main() { int year, month, day; printf("Enter year: "); scanf("%d", &year); printf("Enter month: "); scanf("%d", &month); printf("Enter day: "); scanf("%d", &day);
int dayOfYear = calculateDayOfYear(year, month, day);
printf("Day of the year: %d\n", dayOfYear);
return 0;
}
This program demonstrates how to calculate the day of the year from a given date. The 'isLeapYear' function determines if the input year is a leap year, and 'calculateDayOfYear' sums up the days in each month up to the given date. The program then prints the calculated day of the year.
Note: This program assumes the input values are valid and doesn't include extensive error handling. Consider adding error checking for user input for a more robust program.
原文地址: https://www.cveoy.top/t/topic/bSty 著作权归作者所有。请勿转载和采集!