c++if语句判断闰年
时间: 2023-12-22 16:29:28 浏览: 76
以下是用C++的if语句判断闰年的示例代码:
```cpp
#include <iostream>
using namespace std;
int main() {
int year;
bool leap;
cout << "请输入年份:";
cin >> year;
if (year % 4 == 0) {
if (year % 100 == 0) {
if (year % 400 == 0)
leap = true;
else
leap = false;
} else
leap = true;
} else
leap = false;
if (leap)
cout << year << "是闰年" << endl;
else
cout << year << "不是闰年" << endl;
return 0;
}
```
相关问题
C++用switch+case判断闰年
C++中可以使用switch语句结合case来判断闰年。闰年是指能够被4整除但不能被100整除的年份,或者能够被400整除的年份。下面是一个示例代码:
```cpp
#include <iostream>
using namespace std;
int main() {
int year;
cout << "请输入一个年份:";
cin >> year;
switch (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
case true:
cout << year << "年是闰年。" << endl;
break;
case false:
cout << year << "年不是闰年。" << endl;
break;
}
return 0;
}
```
在上述代码中,我们使用了switch语句来判断闰年。通过计算`year % 4 == 0 && year % 100 != 0 || year % 400 == 0`的结果,如果结果为true,则执行第一个case中的代码,输出该年份是闰年;如果结果为false,则执行第二个case中的代码,输出该年份不是闰年。
用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。在主函数中,用户可以输入一个年份,程序将输出该年份是否为闰年。