简体   繁体   中英

Am I using modulus wrong? My program will always enter the if statement

bool leap = false;
int leapd = 28;

if (year % 100 == 0) {
    if (year % 400 == 0) {
        leap = true;
    }
    else { leap = false; }
}

else if (year % 4 == 0) {
    leap = true;
}
else { leap = false; }
if (leap = true) {
    leapd++;
}

This program decides if the year entered is a leap year or not. I'm not sure why, but the program will always set leap to true in the end.

If the year is divisible by 100, than it is a leap year if it also is divisible by 400.

If it is not divisible by 100, it is only a leap year if you can divide the year by 4.

It should be if (leap == true) for your last if statement. If you fix that, it should work. = is the assignment variable. So in your last if statement, instead of comparing leap and true using == you are assigning leap to true using = .

So your final if statement should actually be:

if (leap == true)
{
    leapd++;
}

The last loop should look like

if (leap == true)
{
    leapd++;
}

The way you currently have it will set leap to True and then evaluate the if . Which will always be True . The condition check should be == .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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