c++编写定义判断闰年的函数
时间: 2024-02-17 14:04:56 浏览: 39
下面是一个使用 C++ 编写的判断闰年的函数:
```c++
#include <iostream>
bool isLeapYear(int year)
{
if (year % 4 == 0) {
if (year % 100 == 0) {
if (year % 400 == 0) {
return true;
}
return false;
}
return true;
}
return false;
}
int main()
{
int year;
std::cout << "请输入要判断的年份:" << std::endl;
std::cin >> year;
if (isLeapYear(year)) {
std::cout << year << " 年是闰年" << std::endl;
} else {
std::cout << year << " 年不是闰年" << std::endl;
}
return 0;
}
```
在函数中,我们首先对年份进行了 4、100 和 400 的判断,如果符合这些条件,则该年是闰年,否则不是闰年。在主函数中,我们通过输入年份来调用该函数,并根据返回值输出判断结果。
相关问题
c++编写 定义判断闰年的函数 本题要求实现判断给定年是否为闰年的函数。 函数接口定义: int leapYear (int year); 其中year是传入的整型参数。当year为闰年时,函数返回1;year不是闰年时返回0。
下面是一个使用 C++ 编写的判断闰年的函数:
```c++
#include <iostream>
int leapYear(int year)
{
if (year % 4 == 0) {
if (year % 100 == 0) {
if (year % 400 == 0) {
return 1;
}
return 0;
}
return 1;
}
return 0;
}
int main()
{
int year;
std::cout << "请输入要判断的年份:" << std::endl;
std::cin >> year;
if (leapYear(year)) {
std::cout << year << " 年是闰年" << std::endl;
} else {
std::cout << year << " 年不是闰年" << std::endl;
}
return 0;
}
```
在函数中,我们首先对年份进行了 4、100 和 400 的判断,如果符合这些条件,则该年是闰年,返回1;否则不是闰年,返回0。在主函数中,我们通过输入年份来调用该函数,并根据返回值输出判断结果。
编写函数 int fun(int n)判断n是否是闰年,定义main函数输入年份,调用fun函数判断,在main函数中输出yes或no
好的,可以使用以下代码实现:
```C++
#include <iostream>
using namespace std;
int fun(int n) {
if ((n % 4 == 0 && n % 100 != 0) || n % 400 == 0) {
return 1; // 是闰年
} else {
return 0; // 不是闰年
}
}
int main() {
int year;
cout << "请输入年份:";
cin >> year;
if (fun(year)) {
cout << "yes" << endl;
} else {
cout << "no" << endl;
}
return 0;
}
```
在函数`fun`中,如果年份能够被4整除且不能被100整除,或者能够被400整除,则认为是闰年,返回1;否则返回0。
在主函数中,先输入年份,再调用`fun`函数判断,如果是闰年,输出"yes",否则输出"no"。
相关推荐
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)