c++ if条件语句入门

  1. if语法(入门)
#include<iostream>
#include<cstdio>
using namespace std;
int main()
{	
   int n; 
   cout<<"Please input number!"<<endl;
   cin>>n;
   if (n%2==0)
   {
   	cout<<"It's is even"<<endl;
   }
   else
   {
   	cout<<"It's is odd"<<endl;
   }
   
   
   return 0;
} 

  1. if语法(解释)
// if 语句里面可以继续嵌套 if else 语句 。 if语句可以单独出现,后面不用跟else。else 与离它最近的if相匹配。
#include<iostream>
#include<cstdio>
using namespace std;
int main()
{
  //定义一个变量 
  int n;
  //c++语法 输入一个变量 并赋值给n; 
  /*
  	
  	if (条件)
  {
  	
  }
  elif (条件)
  {
  	
  } 
  else
  {
  			
  } 
  
  */
  cin>>n; 
  if(n<0)
  {
  	cout<<" n is a negative"<<endl;
  	// 这里的if就是 循环嵌套了 并别 没有跟elif 和 else匹配 证明它可以单独存在 
  	if(n ==-1)
  	{
  		cout<<" n is a -1"<<endl;
  	}
  	
   } 
   
   else if(n ==0)
   {
   	cout<<" n is a zero"<<endl;
   	
   }
   else
   {
   	cout<<"n is a positive"<<endl;
   	
   }
  
  return 0;
}

3.if语法(进阶)

#include<iostream>
#include<cstdio>
using namespace std;
int main()

{
// 题:输入一个年份 判断它是否是 建党建国 10,20,..周年 以及判断它是不是闰年并输出 
// 闰年条件:能整除4且不能整除100 2、能整除400
// 建党时间 1921 建国时间1949 
//定义变量
int year_input;
int Party_building = 1921;
int found_state = 1949;
// 输入提示 及输入
cout<<"Please input year"<<endl;
cin>>year_input;
// 3对条件判断及输出
if(year_input>0)
{
   if ((year_input-Party_building)%10==0)
{
   cout<<"is Party_building anniversary10"<<endl;
}
else
{
   cout<<"is not Party_building anniversary10"<<endl;	
}
if ((year_input-found_state)%10==0)
{
   cout<<"is found_state anniversary10"<<endl;;
}
else
{
   cout<<"is not found_state anniversary10"<<endl;
}
if (((year_input)%400==0) || ((year_input)%100!=0 && (year_input)%4==0 ))
{
   cout<<"is leap year "<<endl;
}
else
{
   cout<<"is not leap year"<<endl;
}

}
else
{
   cout<<"illegal input"<<endl; 
   
}


   return 0;
}
  • 6
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值