解析C++编程中的选择结构和switch语句的用法

2020-01-06 13:39:12刘景俊

易采站长站为您分析解析C++编程中的选择结构和switch语句的用法,是C++入门学习中的基础知识,需要的朋友可以参考下

C++编写选择结构的程序

下面,通过两个实例来说明如何编写较为复杂的C++程序。

【例】编写程序,判断某一年是否为闰年。

 

 
  1. #include <iostream>  using namespace std; 
  2. int main( )  { 
  3. int year;  bool leap; 
  4. cout<<"please enter year:";//输出提示  cin>>year; //输入年份 
  5. if (year%4==0) //年份能被4整除  { 
  6. if(year%100==0)//年份能被4整除又能被100整除  { 
  7. if (year%400==0)//年份能被4整除又能被400整除  leap=true;//闰年,令leap=true(真) 
  8. else  leap=false; 
  9. } //非闰年,令leap=false(假)  else //年份能被4整除但不能被100整除肯定是闰年 
  10. leap=true;  } //是闰年,令leap=true 
  11. else //年份不能被4整除肯定不是闰年  leap=false; //若为非闰年,令leap=false 
  12. if (leap)  cout<<year<<" is "; //若leap为真,就输出年份和“是” 
  13. else  cout<<year<<" is not ";//若leap为真,就输出年份和“不是” 
  14. cout<<" a leap year."<<endl; //输出“闰年”  return 0; 

运行情况如下:

 

 
  1. ① 2005↙  2005 is not a leap year.