![](/img/trans.png)
[英]how to solve this question when a day is set to the first day of the month and decremented, it should become the last day of the previous month?
[英]Understanding code for first day of month function
我在做练习。 它要求我创建月份(当前用户时间)的日历。 我已经在Internet上查询了一些代码,效果很好,但是我不清楚。 特别是year -= month < 3
。 有人可以解释一下吗?
//return the daycode of the first day of month.
int firstDayOfMonth(int month, int year) {
int dow = 0;
int day = 1;
int t[] = { 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 };
year -= month < 3; // I cannot understand this.
cout<<"This is year "<<year<<endl;
dow = ( year + year/4 - year/100 + year/400 + t[month-1] + day) % 7;
return dow;
}
int main()
{
int a;
cout<<firstDayOfMonth(2,2018)<<endl;
return 0;
}
在C ++中,布尔值可以隐式转换为整数,其中false
变为0
, true
变为1
。 (请参阅bool到int的转换 。)
所以year -= month < 3;
等效于:
if (month < 3) {
year -= 1; // true -> 1
} else {
year -= 0; // false -> 0
}
可以简化为:
if (month < 3) {
--year;
}
动机是一月和二月(第1
和2
个月) 在任何leap日之前出现,而其他月份在任何leap日之后,因此将一月和二月视为上一年末是很方便的,将March日添加到整个3月至2月的计算中。
显然,此代码并未针对可读性进行优化。
这意味着:
如果条件(月份<3)为true,则减1。如果条件(月份<3)为false,则减0(年保持不变)
值1和0表示月份和数字比较的错误和正确。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.