用编程判断闰年
编程实现闰年的判断
在很多编程任务中,需要判断给定的年份是否是闰年。闰年的定义是能被4整除但不能被100整除的年份,或者能被400整除的年份。下面是几种常见编程语言的实现示例:
1. 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 = 2024
if is_leap_year(year):
print(f"{year}年是闰年")
else:
print(f"{year}年不是闰年")
```
2. Java
```java
public class LeapYear {
public static boolean isLeapYear(int year) {
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}
public static void main(String[] args) {
int year = 2024;
if (isLeapYear(year)) {
System.out.println(year "年是闰年");
} else {
System.out.println(year "年不是闰年");
}
}
}
```
3. JavaScript
```javascript
function isLeapYear(year) {
return (year % 4 === 0 && year % 100 !== 0) || (year % 400 === 0);
}
let year = 2024;
if (isLeapYear(year)) {
console.log(`${year}年是闰年`);
} else {
console.log(`${year}年不是闰年`);
}
```
4. C
```cpp
include
using namespace std;
bool isLeapYear(int year) {
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}
int main() {
int year = 2024;
if (isLeapYear(year)) {
cout << year << "年是闰年" << endl;
} else {
cout << year << "年不是闰年" << endl;
}
return 0;
}
```
5. C
```csharp
using System;
class Program {
static bool IsLeapYear(int year) {
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}
static void Main(string[] args) {
int year = 2024;
if (IsLeapYear(year)) {
Console.WriteLine($"{year}年是闰年");
} else {
Console.WriteLine($"{year}年不是闰年");
}
}
}
```
以上是几种常见编程语言的闰年判断实现。根据需要选择合适的语言和方法进行实现。