这是我的要求,我需要知道我做对了吗?确定年份是否为闰年算法如果年份可以平均除以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;
}
userInput % 4 == 0 && userInput % 100 ==0
相当于userInput % 400 == 0
和userInput % 4 == 0
然后它绝对是闰年所以不需要检查任何其他条件。
我在C ++中使用过这个。
return((userInput%400)||((userInput%4)&&!(userInput%100)));
更好地利用这个条件进行有效的闰年
(((year%4 == 0) && (year%100 !=0)) || (year%400==0))
这是一个类似的C program to check leap year。
正确!简化:
year % 4
测试的第二个if
bc中移除if
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
我用这个简短的方法:
private static Boolean isLeapYear(int year) {
return year % 4 == 0 ? (year % 100 == 0 ? ( year % 400 == 0 ? true : false) : true) : false ;
}
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)