在我的程序中,我要求用户输入一个日期(只能是整数,如12 31 2019 367)和他们添加到该日期的天数。在我的一个函数中,这正是我正在做的事情。
用户输入12 31 2019 367,程序本应打印1 1 2021,但却打印了1 1 2020(晚了一年)......
我做了什么(抱歉有很多代码,我尽量保持它简单和干净):
int days_in_month[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
void add_days_to_date(int *mm, int *dd, int *yy, int days_left_to_add)
{
int days_left_in_month;
while(days_left_in_month > 0)
{
days_left_in_month = days_in_month[*mm] - *dd;
// days_left_in_month = days_in_month[*mm] - *dd;
if (days_in_month[2] && is_leap_year(*yy) == true)
{
days_left_in_month++;
}
} // end while
printf("after while\n");
if(days_left_to_add > days_left_in_month)
{
days_left_to_add -= days_left_in_month;
*dd = 1;
if(*mm == 12)
{
*mm = 1;
(*yy)++;
}
else
{
(*mm)++;
}
}
else
{
*dd += days_left_to_add;
days_left_to_add = 0;
}
}
int main()
{
int mm, dd, yy, days_left_to_add;
printf("Please enter a date between the years 1800 and 10000 in the format mm dd yy and provide the number of days to add to this date:\n");
scanf("%d %d %d %d", &mm, &dd, &yy, &days_left_to_add);
// printf("\nREAD\n");
//These are pointers, so they have to be at certain location i.e. int* mm = &mm
add_days_to_date(&mm, &dd, &yy, days_left_to_add);
printf("%d %d %d\n", mm, dd, yy);
}
输入后得到的结果:
输入:2019年12月31日367
产量:1 1 2020(本应为1 1 2021)
1条答案
按热度按时间fcy6dtqo1#
函数中的循环需要是
while (days_left_to_add > 0)
,并且应该覆盖整个函数(然后需要做一些小的调整),实际上,你只需要加上一个月,假设你的输入是2019-12-31,你就会得到2020-01-01。您的代码应该验证输入日期。
这段代码可以工作,至少对于许多类似于您的示例的测试用例是这样。
样本运行(根据
ad41.c
创建的程序ad41
):