计算机语言怎么判断闰年

时间:2025-01-24 14:10:32 单机攻略

判断闰年的规则如下:

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.*;

public class LeapYear {

public static void main(String[] args) {

Scanner in = new Scanner(System.in);

System.out.println("请输入年份,回车结束");

int year = in.nextInt();

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

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

} else {

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

}

}

}

```

C语言

```c

include

int main() {

int year;

printf("请输入年份: ");

scanf("%d", &year);

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

printf("%d是闰年", year);

} else {

printf("%d是平年", year);

}

return 0;

}

```

C++

```cpp

include

bool isLeapYear(int year) {

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

}

int main() {

int year;

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

std::cin >> year;

if (isLeapYear(year)) {

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

} else {

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

}

return 0;

}

```

Bash

```bash

!/bin/bash

read -p "请输入年份:" year

if [ "$((year % 4))" -eq 0 -a "$((year % 100))" -ne 0 ] || [ "$((year % 400))" -eq 0 ]; then

echo "$year 是闰年!"

else

echo "$year 不是闰年!"

fi

```

这些代码示例都遵循了闰年的判断规则,并根据输入的年份输出是否为闰年。你可以选择任意一种编程语言来实现这个功能。