- 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;
}
- 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;
}