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

huangapple 未分类评论69阅读模式
标题翻译

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

整数(year)为9000,本应返回false,但实际上返回了true。出了什么问题?

英文翻译
public static boolean isLeapYear(int year) {
	if(year &lt; 1 || year &gt; 9999) {
		return false;
	}else {
		if(year % 4 == 0) {
			return true;
		}if(year % 100 != 0 &amp;&amp; year % 400 == 0) {
			return true;
		}else {
			return false;
		}
	}
}

The integer (year) is 9000, it should have returned false but got true instead. What went wrong?

答案1

得分: 0

答案在第5行:

year % 4 == 0

这个表达式的结果为真,因为9000可以被4整除。

英文翻译

The anser is on line 5:

year % 4 == 0

This evaluates to true because 9000 is divisible by 4.

答案2

得分: 0

正如其他人所说,当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;

请注意,以上代码是用于计算闰年的逻辑。

英文翻译

As others have said, the year%4 evaluates to 0 for year=9000.
Here's the logic for computing a leap year

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

huangapple
  • 本文由 发表于 2020年3月16日 23:03:16
  • 转载请务必保留本文链接:https://java.coder-hub.com/60708348.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定