【新手教程】关于if语句
2026-02-13 16:14:40
发布于:浙江
这是一个争对新手对关于if语句的学习
if语句
if(条件){
执行区域
}
上面就是个if语句的构架,而if语句的概念是:
当
if的括号里的条件成立时,则执行下面的代码,否则不执行
虽然我认为有些人听起来不模糊,但为了以防万一,决定弄个例子
1
if(true/*bool值,这里相当于条件成立*/){
cout<<"OK1"<<endl;
}
cout<<"OK2"<<endl;
输出区
OK1
OK2
2
if(false/*bool值,这里相当于条件不成立*/){
cout<<"OK1"<<endl;
}
cout<<"OK2"<<endl;
输出区
OK2
这就是成立与不成立的差别
这里的代码是简化版,当然需要考虑头文件、命名空间、主函数、缩进等其他因素
if—else 语句
if(条件){
执行区域
}
else{
执行区域
}
上面的是if-else的构架,而if-else语句的概念是:
当
if语句的括号里的条件成立时,执行if语句下面的代码,否则执行else语句下面的代码
e.g.
1
if(true){
cout<<"OK1"<<endl;
}
else{
cout<<"OK2"<<endl;
}
cout<<"OK3"<<endl;
输出区
OK1
OK3
2
if(false){
cout<<"OK1"<<endl;
}
else{
cout<<"OK2"<<endl;
}
cout<<"OK3"<<endl;
输出区
OK2
OK3
warning:
else不能单独使用,例如:
else/*ERROR*/{
cout<<"CP"<<endl;
}
我们从例子看出来有差别
if-else if-else 语句
if(条件){
执行区域
}
else if(条件){
执行区域
}
//……(或只有1个else if语句)
else{
执行区域
}
上面是if-else if-else语句的构架,而这个语句的概念是:
当
if语句里的括号的条件成立时,则执行if语句的下面,当if语句不成立时,则继续判断else if语句的条件,若成立,则执行else if语句里的下面,若不成立,则继续判断else if语句或执行else语句的下方,以此类推
e.g
1
if(true){
cout<<"OK1"<<endl;
}
else if(false){
cout<<"OK2"<<endl;
}
else{
cout<<"OK3"<<endl;
}
输出区
OK1
2
if(false){
cout<<"OK1"<<endl;
}
else if(true){
cout<<"OK2"<<endl;
}
else{
cout<<"OK3"<<endl;
}
输出区
OK2
3
if(false){
cout<<"OK1"<<endl;
}
else if(false){
cout<<"OK2"<<endl;
}
else if(true){
cout<<"OK3"<<endl;
}
else{
cout<<"OK4"<<endl;
输出区
OK3
4
if(false){
cout<<"OK1"<<endl;
}
else if(false){
cout<<"OK2"<<endl;
}
else{
cout<<"OK3"<<endl;
}
输出区
OK3
5
if(true){
cout<<"OK1"<<endl;
}
else if(true){
cout<<"OK2"<<endl;
}
else{
cout<<"OK3"<<endl;
}
输出区
OK1
因为今天太肝了,明日更新
全部评论 3
ddd
2026-02-13 来自 浙江
0ddd
2026-02-13 来自 浙江
0ddd
2026-02-13 来自 浙江
0




















有帮助,赞一个