编程怎么判断一个年份

时间:2025-01-24 13:20:44 游戏攻略

判断一个年份是否为闰年,可以使用以下规则:

1. 如果年份能被4整除但不能被100整除,则为普通闰年。

2. 如果年份能被400整除,则为世纪闰年。

基于这些规则,以下是一些不同编程语言中判断闰年的示例代码:

Python 示例代码:

```python

def is_leap_year(year):

if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):

return True

else:

return False

year = int(input("请输入年份: "))

if is_leap_year(year):

print(f"{year}是闰年")

else:

print(f"{year}不是闰年")

```

Java 示例代码:

```java

import java.util.Scanner;

public class LeapYear {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.print("请输入年份: ");

int year = sc.nextInt();

if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {

System.out.println(year + "是闰年");

} else {

System.out.println(year + "不是闰年");

}

sc.close();

}

}

```

C++ 示例代码:

```cpp

include

int main() {

int year;

std::cout << "请输入年份: ";

std::cin >> year;

if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {

std::cout << year << "是闰年" << std::endl;

} else {

std::cout << year << "不是闰年" << std::endl;

}

return 0;

}

```

JavaScript 示例代码:

```javascript

function isLeapYear(year) {

return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;

}

const year = parseInt(prompt("请输入年份:"));

if (isLeapYear(year)) {

console.log(year + "是闰年");

} else {

console.log(year + "不是闰年");

}

```

Ruby 示例代码:

```ruby

def leap_year?(year)

(year % 4 == 0 && year % 100 != 0) || year % 400 == 0

end

puts "请输入年份:"

year = gets.chomp.to_i

if leap_year?(year)

puts "{year}是闰年"

else

puts "{year}不是闰年"

end

```

这些示例代码都遵循了上述的闰年判断规则,并通过不同的编程语言实现了这一功能。你可以选择适合你的编程语言进行尝试。