标题翻译
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 < 1 || year > 9999) {
return false;
}else {
if(year % 4 == 0) {
return true;
}if(year % 100 != 0 && 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
专注分享java语言的经验与见解,让所有开发者获益!
评论