C 语言中的决策

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

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

  • if声明
  • switch声明
  • 条件运算符语句(? :运算符)
  • goto声明

if语句进行决策

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

  1. 简单if语句
  2. if....else声明
  3. 嵌套if....else 语句
  4. 使用else if语句

简单if语句

简单if语句的一般形式是,

if(expression)
{
    statement inside;
}
    statement outside;

如果表达式返回真,则执行语句-内部,否则跳过语句-内部,只执行语句-外部

示例:

#include <stdio.h>

void main( )
{
    int x, y;
    x = 15;
    y = 13;
    if (x > y )
    {
        printf("x is greater than y");
    }
}

x 大于 y


if...else声明

简单if...else语句的一般形式是,

if(expression)
{
    statement block1;
}
else
{
    statement block2;
}

如果表达式为真,则执行语句-区块 1 ,否则跳过语句-区块 1 ,执行语句-区块 2

示例:

#include <stdio.h>

void main( )
{
    int x, y;
    x = 15;
    y = 18;
    if (x > y )
    {
        printf("x is greater than y");
    }
    else
    {
        printf("y is greater than x");
    }
}

y 大于 x


嵌套if....else语句

嵌套if...else语句的一般形式是,

if( expression )
{
    if( expression1 )
    {
        statement block1;
    }
    else 
    {
        statement block2;
    }
}
else
{
    statement block3;
}

如果表达式为假,则执行语句-块 3 ,否则继续执行并进入第一个if内部执行下一个if块的检查,其中如果表达式 1 为真,则执行语句-块 1 ,否则执行语句-块 2

示例:

#include <stdio.h>

void main( )
{
    int a, b, c;
    printf("Enter 3 numbers...");
    scanf("%d%d%d",&a, &b, &c);
    if(a > b)
    { 
        if(a > c)
        {
            printf("a is the greatest");
        }
        else 
        {
            printf("c is the greatest");
        }
    }
    else
    {
        if(b > c)
        {
            printf("b is the greatest");
        }
        else
        {
            printf("c is the greatest");
        }
    }
}

else if梯子

else 的一般形式——如果梯子是,

if(expression1)
{
    statement block1;
}
else if(expression2) 
{
    statement block2;
}
else if(expression3 ) 
{
    statement block3;
}
else 
    default statement;

这个表达式是从(梯子的)顶部向下测试的。一旦发现一个条件,与之相关的语句就被执行。

示例:

 #include <stdio.h>

void main( )
{
    int a;
    printf("Enter a number...");
    scanf("%d", &a);
    if(a%5 == 0 && a%8 == 0)
    {
        printf("Divisible by both 5 and 8");
    }  
    else if(a%8 == 0)
    {
        printf("Divisible by 8");
    }
    else if(a%5 == 0)
    {
        printf("Divisible by 5");
    }
    else 
    {
        printf("Divisible by none");
    }
}

需要记住的要点

  1. In if statement, a single statement can be included without enclosing it into curly braces { ... }

    int a = 5;
    if(a > 4)
        printf("success");
    

    上面的情况不需要花括号,但是如果我们在if条件里面有一个以上的语句,那么我们必须把它们括在花括号里面。

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

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

    if(27)
        printf("hello");
    

    在上例中,将打印你好