判断是否为闰年(C++)

本文介绍了一种用于判断闰年的算法,详细解释了闰年的定义及其判断条件。文章提供了完整的C++代码实现,包括一个循环机制,允许用户多次输入年份进行判断,并选择是否继续操作。

是闰年的情况:

能够被400整除的年份是闰年;

能够被4整除且不能被100整除的年份是闰年;

	if ((year%400==0) || ((year%100!=0)&&(year%4==0)))
	{
		//是闰年 
		cout<<"is leap year"<<endl;
	}
	else
	{
		//不是闰年 
		cout<<"not leap year!"<<endl;
	}
	

完整代码:

#include<iostream> 
using namespace std;

int main()
{
	int year;
	int num;
	bool continue_loop = true;    //控制循环是否继续检查年份 
	
	while(continue_loop)
	{
		cout<<"请输入年份: "<<endl;
	 	cin>>year; 
	
		if ((year%400==0) || ((year%100!=0)&&(year%4==0)))
		{
			//是闰年 
			cout<<"is leap year!\n"<<endl;
		}
		else
		{
			//不是闰年 
			cout<<"not leap year!\n"<<endl;
		}
		
		cout<<"需要继续判断?(输入“1”继续|输入其他退出)"<<endl; 
		cin>>num;
		cout<<endl;
		
		if(num!=1)
		{
			cout<<"\n已退出!"<<endl;
			continue_loop = false;	
		} 
	} 
	
	return 0;
}

 

以下为几种使用C++语言判断一个年份是否闰年的实现代码: ### 方法一:使用函数封装判断逻辑 ```cpp #include <iostream> // 判断给定的年份是否闰年 bool isLeapYear(int year) { if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) { return true; } else { return false; } } int main() { // 测试示例 int year; std::cout << "输入四位年(如2000): "; std::cin >> year; if (isLeapYear(year)) { std::cout << year << " 是闰年" << std::endl; } else { std::cout << year << " 不是闰年" << std::endl; } return 0; } ``` ### 方法二:使用嵌套的if语句判断 ```cpp #include <iostream> int main() { int year; std::cout << "请输入一个年份:"; std::cin >> year; if (year % 4 == 0) { if (year % 100 == 0) { if (year % 400 == 0) { std::cout << year << "是闰年。" << std::endl; } else { std::cout << year << "不是闰年。" << std::endl; } } else { std::cout << year << "是闰年。" << std::endl; } } else { std::cout << year << "不是闰年。" << std::endl; } return 0; } ``` ### 方法三:简洁的判断方式 ```cpp #include <iostream> using namespace std; int main() { int year; cin >> year; if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) { cout << "yes" << endl; } else { cout << "no" << endl; } return 0; } ``` ### 方法四:使用标准输入输出库 ```cpp #include <stdio.h> int main() { int year = 0; scanf("%d", &year); // 输入年份 if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) { printf("%d是闰年\n", year); } else { printf("%d不是闰年\n", year); } return 0; } ``` ### 方法五:使用if语句嵌套并设置标志变量 ```cpp #include <stdio.h> int main() { int year, leap; printf("enter year:"); scanf("%d", &year); if (year % 4 == 0) { if (year % 100 == 0) { if (year % 400 == 0) leap = 1; else leap = 0; } else leap = 1; } else leap = 0; if (leap) printf("%d is ", year); else printf("%d is not ", year); printf("a leap year.\n"); return 0; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值