题解 | #计算日期到天数转换#
计算日期到天数转换
https://www.nowcoder.com/practice/769d45d455fe40b385ba32f97e7bcded
#include <stdio.h> // 获取某年某月的天数 int GetMonthDay(int year, int month) { int monthArray[13] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; if (month == 2 && ((year % 400 == 0) || (year % 4 == 0 && year % 100 != 0))) { return 29; } return monthArray[month]; } int main() { int year, month, day; // 循环读取输入的年份、月份和日期 while (scanf("%d %d %d", &year, &month, &day) != EOF) { int ans = 0; // 计算给定日期与该年的1月1日之间的天数差 for (int m = 1; m < month; m++) { ans += GetMonthDay(year, m); } ans += day; // 输出结果 printf("%d\n", ans); } return 0; }
在这段代码中,我们通过循环将给定日期之前的每个月份的天数累加到ans
变量中,然后再加上给定日期的天数,得到最终的天数差。代码中的循环可以处理多组输入,直到遇到 EOF
(End of File)。最后,我们使用printf
函数打印结果。