C++ 中的决策——ifelseelse if

原文:https://www.studytonight.com/cpp/decision-making-in-cpp

决策是根据特定条件决定语句的执行顺序,或者重复一组语句,直到满足特定条件。C++ 通过支持以下语句来处理决策,

  • if 语句
  • 切换语句
  • 条件运算符语句
  • 转到语句

if语句进行决策

if语句可以根据测试条件的复杂程度以不同的形式实现。不同的形式是,

  1. 简单的 if 语句
  2. 如果....else 语句
  3. 嵌套如果....else 语句
  4. 否则如果声明

简单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";
        }
    }
}

以上代码将根据abc变量的值打印不同的语句。


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 整除


需要记住的要点

  1. 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 条件内

  2. if条件的表达式中必须使用==进行比较,如果使用=,表达式将始终返回 true ,因为它执行赋值而不是比较。

  3. Other than 0(zero), all other positive numeric values are considered as true.

    if(27)
        cout << "hello";
    

    你好