C Exercise Example 4
Title:Input a certain year, month, and day, and determine which day of the year this day is?
Program analysis:Taking March 5 as an example, first add up the first two months, then add 5 days to get the day of the year. Special case: in a leap year, if the input month is greater than 3, an extra day needs to be added.
Example
#include <stdio.h>
int isLeapYear(int year) {
// Leap year rule: divisible by 4 and (not divisible by 100 or divisible by 400)
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
return 1;
}
return 0;
}
int main() {
int year, month, day;
int daysInMonth[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int totalDays = 0;
printf("Please enter year, month, and day (format: year month day):");
scanf("%d %d %d", &year, &month, &day);
// Determine whether it is a leap year
if (isLeapYear(year)) {
daysInMonth[1] = 29; // February has 29 days in a leap year
}
// Calculate the number of days from January 1 to the input date
for (int i = 0; i < month - 1; i++) {
totalDays += daysInMonth[i];
}
totalDays += day; // Add the number of days of the current month
printf("%d year %d month %d day is the %dth day of the year\n", year, month, day, totalDays);
return 0;
}
The output of the above example is:
请输入年份、月份和日期(格式:年 月 日):2024 3 5 2024年3月5日是该年的第65天
Optimize it by adding a date check:
Example
#include <stdio.h>
int isLeapYear(int year) {
// Leap year rule: divisible by 4 and (not divisible by 100 or divisible by 400)
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
return 1;
}
return 0;
}
int main() {
int year, month, day;
int daysInMonth[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
printf("Please enter year, month, and day (format: year month day):");
if (scanf("%d %d %d", &year, &month, &day) != 3) {
printf("Invalid input, please enter the correct year, month, and date.\n");
return 1;
}
// Check if the year is valid
if (year <= 0) {
printf("Invalid year, please enter a positive integer.\n");
return 1;
}
// Check if the month is valid
if (month < 1 || month > 12) {
printf("Invalid month, please enter a number between 1 and 12.\n");
return 1;
}
// Check if the date is valid
if (isLeapYear(year)) {
daysInMonth[1] = 29; // February has 29 days in a leap year
}
if (day < 1 || day > daysInMonth[month - 1]) {
printf("Invalid date, please enter a valid date.\n");
return 1;
}
// Calculate the number of days from January 1 to the input date
int totalDays = 0;
for (int i = 0; i < month - 1; i++) {
totalDays += daysInMonth[i];
}
totalDays += day; // Add the number of days of the current month
printf("%d year %d month %d day is the %dth day of the year\n", year, month, day, totalDays);
return 0;
}
The output of the above example is:
请输入年份、月份和日期(格式:年 月 日):2024 2 32 日期不合法,请输入有效的日期。other extensions