确定闰年

问题描述 投票:1回答:6

这是我的要求,我需要知道我做对了吗?确定年份是否为闰年算法如果年份可以平均除以4,那么它是闰年o除非年份可以平均除以100,否则它不是闰年除非年份可以平均除以400,然后是闰年否则,它不是闰年

private static boolean isLeapYear(int userInput){
        boolean leapYear= false;

        if (userInput % 4 == 0 ){
            leapYear = true;

            if (userInput % 4 == 0 && userInput % 100 ==0) {
                leapYear = false;

                if(userInput % 400 == 0){
                    leapYear = true;
                }
            }
        }
        else {
            leapYear = false;
        }

        return leapYear;
        }
leap-year
6个回答
-1
投票

userInput % 4 == 0 && userInput % 100 ==0相当于userInput % 400 == 0

userInput % 4 == 0然后它绝对是闰年所以不需要检查任何其他条件。


0
投票

我在C ++中使用过这个。

return((userInput%400)||((userInput%4)&&!(userInput%100)));


0
投票

更好地利用这个条件进行有效的闰年 (((year%4 == 0) && (year%100 !=0)) || (year%400==0))

这是一个类似的C program to check leap year


0
投票

正确!简化:

  1. 从已经在第一个year % 4测试的第二个if bc中移除if
  2. 删除else bc已经在顶部设置了leap = False

蟒蛇:

def is_leap(year):
    leap = False

    if year % 4 == 0:
        leap = True

        if year % 100 == 0:
            leap = False

            if year % 400 == 0:
                leap = True

    return leap

1号线:

def is_leap(year):
    return year % 4 == 0 and year % 100 != 0 or year % 400 == 0

0
投票

我用这个简短的方法:

private static Boolean isLeapYear(int year) {
        return year % 4 == 0 ? (year % 100 == 0 ? ( year % 400 == 0 ? true : false) : true) : false ;
    }

0
投票
year = int(input("Enter year to determine if it is a leap year"))

def leap_year(year):
    """This is a function to determine if a year
       is a leap year"""
    if year%4==0 and year%100!=0:
        print("This is a Leap year")
        if year%400==0:
            print ("This is a Leap year")
    else:
        print ("This is not a leap year")    


leap_year(year)
© www.soinside.com 2019 - 2024. All rights reserved.