用C++判断年份是否为闰年
时间: 2023-09-22 10:07:43 浏览: 360
可以使用以下代码来判断年份是否为闰年:
```c++
#include <iostream>
using namespace std;
int main()
{
int year;
cout << "请输入一个年份: ";
cin >> year;
if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0)
{
cout << year << "年是闰年" << endl;
}
else
{
cout << year << "年不是闰年" << endl;
}
return 0;
}
```
判断闰年的规则为:能被4整除但不能被100整除,或者能被400整除的年份是闰年。
相关问题
用c++编写判断是否为闰年
判断是否为闰年的C++代码如下:
```cpp
#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::cin >> year;
if (isLeapYear(year)) {
std::cout << year << "年是闰年" << std::endl;
} else {
std::cout << year << "年不是闰年" << std::endl;
}
return 0;
}
```
这段代码中,使用了嵌套的 if-else 语句来判断是否为闰年。根据公历闰年的定义,满足以下条件之一的年份即为闰年:
1. 能被4整除但不能被100整除;
2. 能被400整除。
如果满足上述条件之一,则返回 true,否则返回 false。在主函数中,用户可以输入一个年份,程序将输出该年份是否为闰年。
用c++写一个程序判断输入年份是否为闰年
以下是用 C 语言编写的判断输入年份是否为闰年的程序:
```c
#include <stdio.h>
int main() {
int year;
printf("请输入一个年份:");
scanf("%d", &year);
if((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
printf("%d年是闰年\n", year);
} else {
printf("%d年不是闰年\n", year);
}
return 0;
}
```
只需要输入一个年份,程序就会输出该年份是否是闰年。如果是闰年,会输出“X年是闰年”;如果不是闰年,会输出“X年不是闰年”,其中 X 表示用户输入的年份。