繁体   English   中英

为什么这个 if 语句返回值 true?

[英]Why does this if statement return the value true?

public static boolean isLeapYear(int year) {
    if(year < 1 || year > 9999) {
        return false;
    }else {
        if(year % 4 == 0) {
            return true;
        }if(year % 100 != 0 && year % 400 == 0) {
            return true;
        }else {
            return false;
        }
    }
}

整数(年)是 9000,它应该返回 false 却变成了 true。 什么地方出了错?

答案在第 5 行:

year % 4 == 0

这评估为真,因为 9000 可以被 4 整除。

正如其他人所说,对于 year=9000,year%4 的计算结果为 0。 这是计算闰年的逻辑

bool isLeap = false;
if (year % 4 == 0) {
    if (year % 100 == 0) {
        if (year % 400 == 0) {
            isLeap = true;
        }
        else {
            isLeap = false;
        }
    }
    else {
        isLeap = true;
    }
}
else {
    isLeap = false;
}
return isLeap

暂无
暂无

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

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