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

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

Why does this if statement return the value true?

问题

  1. public static boolean isLeapYear(int year) {
  2. if(year < 1 || year > 9999) {
  3. return false;
  4. } else {
  5. if(year % 4 == 0) {
  6. return true;
  7. }
  8. if(year % 100 != 0 && year % 400 == 0) {
  9. return true;
  10. } else {
  11. return false;
  12. }
  13. }
  14. }

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

英文翻译
  1. public static boolean isLeapYear(int year) {
  2. if(year &lt; 1 || year &gt; 9999) {
  3. return false;
  4. }else {
  5. if(year % 4 == 0) {
  6. return true;
  7. }if(year % 100 != 0 &amp;&amp; year % 400 == 0) {
  8. return true;
  9. }else {
  10. return false;
  11. }
  12. }
  13. }

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

答案1

得分: 0

答案在第5行:

  1. year % 4 == 0

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

英文翻译

The anser is on line 5:

  1. year % 4 == 0

This evaluates to true because 9000 is divisible by 4.

答案2

得分: 0

正如其他人所说,当year=9000时,year%4的值为0。
以下是计算闰年的逻辑:

  1. bool isLeap = false;
  2. if (year % 4 == 0) {
  3. if (year % 100 == 0) {
  4. if (year % 400 == 0) {
  5. isLeap = true;
  6. }
  7. else {
  8. isLeap = false;
  9. }
  10. }
  11. else {
  12. isLeap = true;
  13. }
  14. }
  15. else {
  16. isLeap = false;
  17. }
  18. return isLeap;

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

英文翻译

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

  1. bool isLeap = false;
  2. if (year % 4 == 0) {
  3. if (year % 100 == 0) {
  4. if (year % 400 == 0) {
  5. isLeap = true;
  6. }
  7. else {
  8. isLeap = false;
  9. }
  10. }
  11. else {
  12. isLeap = true;
  13. }
  14. }
  15. else {
  16. isLeap = false;
  17. }
  18. 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:

确定