C Ejemplo de práctica 4

100 ejemplos clásicos en lenguaje C

Título:Ingresa un año, mes y día, y determina qué día del año es esa fecha.

Análisis del programa:Tomando el 5 de marzo como ejemplo, primero se suman los dos meses anteriores y luego se añaden 5 días para obtener el día del año. En casos especiales, si es año bisiesto y el mes ingresado es mayor que 3, se debe considerar añadir un día más.

Ejemplo

#include <stdio.h> int isLeapYear(int year) { // Regla para determinar año bisiesto: divisible por 4 y (no divisible por 100 o divisible por 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("Por favor ingresa año, mes y día (formato: año mes día):"); scanf("%d %d %d", &year, &month, &day); // Determina si es año bisiesto if (isLeapYear(year)) { daysInMonth[1] = 29; // Febrero tiene 29 días en año bisiesto } // Calcula los días desde el 1 de enero hasta la fecha ingresada for (int i = 0; i < month - 1; i++) { totalDays += daysInMonth[i]; } totalDays += day; // Suma los días del mes actual printf("%d año %d mes %d día es el día %d del año\n", year, month, day, totalDays); return 0; }

El resultado del ejemplo anterior es:

请输入年份、月份和日期(格式:年 月 日):2024 3 5
2024年3月5日是该年的第65天

Optimizado, con validación de la fecha:

Ejemplo

#include <stdio.h> int isLeapYear(int year) { // Regla para determinar año bisiesto: divisible por 4 y (no divisible por 100 o divisible por 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("Por favor ingresa año, mes y día (formato: año mes día):"); if (scanf("%d %d %d", &year, &month, &day) != 3) { printf("Entrada no válida, por favor ingresa un año, mes y día correctos.\n"); return 1; } // Verifica si el año es válido if (year <= 0) { printf("Año no válido, por favor ingresa un número entero positivo.\n"); return 1; } // Verifica si el mes es válido if (month < 1 || month > 12) { printf("Mes no válido, por favor ingresa un número entre 1 y 12.\n"); return 1; } // Verifica si el día es válido if (isLeapYear(year)) { daysInMonth[1] = 29; // Febrero tiene 29 días en año bisiesto } if (day < 1 || day > daysInMonth[month - 1]) { printf("Fecha no válida, por favor ingresa una fecha válida.\n"); return 1; } // Calcula los días desde el 1 de enero hasta la fecha ingresada int totalDays = 0; for (int i = 0; i < month - 1; i++) { totalDays += daysInMonth[i]; } totalDays += day; // Suma los días del mes actual printf("%d año %d mes %d día es el día %d del año\n", year, month, day, totalDays); return 0; }

El resultado del ejemplo anterior es:

请输入年份、月份和日期(格式:年 月 日):2024 2 32
日期不合法,请输入有效的日期。

100 ejemplos clásicos en lenguaje C

Otras extensiones