我在做练习。它要求我创建一个包含月份、年份的日历,这是当前用户的时间。我在网上查过一些代码,运行得很好,但我不太明白。尤其是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;
}发布于 2018-10-23 09:16:04
在C++中,布尔值可以隐式转换为整数,false变为0,true变为1。(请参阅bool to int conversion。)
所以year -= month < 3;等同于:
if (month < 3) {
year -= 1; // true -> 1
} else {
year -= 0; // false -> 0
}它可以简化为:
if (month < 3) {
--year;
}这样做的动机是,1月和2月(月份1和2)在任何闰日之前,而其他月份在任何闰日之后,因此可以方便地将1月和2月视为前一年的年底,并将闰日添加到整个3月到2月的计算中。
这段代码显然没有针对可读性进行优化。
发布于 2018-10-23 09:22:10
这意味着:
如果条件(月< 3)为真,则减1。如果条件(月< 3)为假,则减0(年保持不变)
值1和0表示月份和数字比较的false和true。
https://stackoverflow.com/questions/52939723
复制相似问题