简体   繁体   English

了解每月第一天功能的代码

[英]Understanding code for first day of month function

I'm doing a practice exercise. 我在做练习。 It asks me to create a calendar of the month, year which is the current user time. 它要求我创建月份(当前用户时间)的日历。 I have looked up some code on the Internet, it works well, but I can't understand it clearly. 我已经在Internet上查询了一些代码,效果很好,但是我不清楚。 Especially the line year -= month < 3 . 特别是year -= month < 3 Can someone explain it, please? 有人可以解释一下吗?

//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;
}

In C++, boolean values can be implicitly converted to integers, with false becoming 0 and true becoming 1 . 在C ++中,布尔值可以隐式转换为整数,其中false变为0true变为1 (See bool to int conversion .) (请参阅bool到int的转换 。)

So year -= month < 3; 所以year -= month < 3; is equivalent to: 等效于:

if (month < 3) {
    year -= 1; // true -> 1
} else {
    year -= 0; // false -> 0
}

which can be simplified to: 可以简化为:

if (month < 3) {
    --year;
}

The motivation is that January and February (months 1 and 2 ) come before any leap day, while the other months come after any leap day, so it's convenient to treat January and February as being at the end of the previous year, and let the leap day be added to the calculation for the entire March-to-February year. 动机是一月和二月(第12个月) 任何leap日之前出现,而其他月份任何leap日之后,因此将一月和二月视为上一年末是很方便的,将March日添加到整个3月至2月的计算中。

This code is obviously not optimized for readability. 显然,此代码并未针对可读性进行优化。

What that means is: 这意味着:

if the condition (month < 3) is true, then decrement by 1. if the condition (month < 3) is false, then decrement by 0 (year stays the same) 如果条件(月份<3)为true,则减1。如果条件(月份<3)为false,则减0(年保持不变)

The value of 1 & 0 represent false & true of the month & number comparison. 值1和0表示月份和数字比较的错误和正确。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM