用天数减去准确的月份

Deduce the accurate month by the number of the days

本文关键字:      更新时间:2023-10-16

我有一个函数,可以从给定的天数(天>0&天<366(中提取月份:

int findMonth(int days)
{
int i, months[] = {31,28,31,30,31,30,31,31,30,31,30,31};
for (i = 0; i < 12 && days > 0;i++)
days -= months[i];
return i;    
}

有没有更合理的方法来推导它?(我忽略了闰年(

如果你想缩短它,我认为你做不到。如果你只是想要一些不同的东西,也许更接近C++,你可以试试这个:

int findMonth(int days) {
int i = 0, months[] = {31,28,31,30,31,30,31,31,30,31,30,31};
return std::count_if(std::begin(months), std::end(months), [&i, &days](int x) { return (i += x) - x <= days; });
}

或使用std::vector:

int findMonth(int days) {
int i = 0;
std::vector<int> months = {31,28,31,30,31,30,31,31,30,31,30,31};
return std::count_if(months.begin(), months.end(), [&i, &days](int x) { return (i += x) - x <= days; });   
}
相关文章:
  • 没有找到相关文章