C++ 中的决策——if
,else
和else if
决策是根据特定条件决定语句的执行顺序,或者重复一组语句,直到满足特定条件。C++ 通过支持以下语句来处理决策,
- if 语句
- 切换语句
- 条件运算符语句
- 转到语句
用if
语句进行决策
if
语句可以根据测试条件的复杂程度以不同的形式实现。不同的形式是,
- 简单的 if 语句
- 如果....else 语句
- 嵌套如果....else 语句
- 否则如果声明
简单if
语句
简单的 if 语句的一般形式是,
if(expression)
{
statement-inside;
}
statement-outside;
如果表达式为真,则执行‘语句-内部’,否则跳过‘语句-内部’,只执行‘语句-外部’。
示例:
#include< iostream.h>
int main( )
{
int x,y;
x=15;
y=13;
if (x > y )
{
cout << "x is greater than y";
}
}
x 大于 y
if...else
声明
简单的一般形式如果...否则的说法是,
if(expression)
{
statement-block1;
}
else
{
statement-block2;
}
如果“表达式”为真或返回真,则执行“语句块 1”,否则跳过“语句块 1”,执行“语句块 2”。
示例:
void main( )
{
int x,y;
x=15;
y=18;
if (x > y )
{
cout << "x is greater than y";
}
else
{
cout << "y is greater than x";
}
}
y 大于 x
嵌套if....else
语句
嵌套的一般形式如果...否则的说法是,
if(expression)
{
if(expression1)
{
statement-block1;
}
else
{
statement-block2;
}
}
else
{
statement-block3;
}
如果“表达式”为假或返回假,则执行“语句块 3”,否则执行将进入if
条件并检查“表达式 1”。那么如果“表达式 1”为真或返回真,则执行“语句块 1”,否则执行“语句块 2”。
示例:
void main( )
{
int a,b,c;
cout << "enter 3 number";
cin >> a >> b >> c;
if(a > b)
{
if( a > c)
{
cout << "a is greatest";
}
else
{
cout << "c is greatest";
}
}
else
{
if( b> c)
{
cout << "b is greatest";
}
else
{
cout << "c is greatest";
}
}
}
以上代码将根据a
、b
和c
变量的值打印不同的语句。
else-if
梯子
else 的一般形式——如果梯子是,
if(expression 1)
{
statement-block1;
}
else if(expression 2)
{
statement-block2;
}
else if(expression 3 )
{
statement-block3;
}
else
default-statement;
这个表达式是从(梯子的)顶部向下测试的。一旦找到真正的条件,就执行与之关联的语句。
示例:
void main( )
{
int a;
cout << "enter a number";
cin >> a;
if( a%5==0 && a%8==0)
{
cout << "divisible by both 5 and 8";
}
else if( a%8==0 )
{
cout << "divisible by 8";
}
else if(a%5==0)
{
cout << "divisible by 5";
}
else
{
cout << "divisible by none";
}
}
如果为变量a
输入值 40 ,那么输出将是:
可被 5 和 8 整除
需要记住的要点
In
if
statement, a single statement can be included without enclosing it into curly braces{ }
.int a = 5; if(a > 4) cout << "success";
成功
上面的情况不需要花括号,但是如果我们在
if
条件中有一个以上的语句,那么我们必须将它们包含在花括号中,否则只会考虑if
条件之后的第一个语句。int a = 2; if(a > 4) cout << "success"; // below statement is outside the if condition cout << "Not inside the if condition"
不在 if 条件内
if
条件的表达式中必须使用==
进行比较,如果使用=
,表达式将始终返回 true ,因为它执行赋值而不是比较。Other than 0(zero), all other positive numeric values are considered as true.
if(27) cout << "hello";
你好