if语句(初学者)

用if语句可以构成分支结构。它根据给定的条件进行判断,以决定执行某个分支程序段。C语言的if语句有三种基本形式。

1、基本形式:if(表达式)语句

其语义是:如果表达式的值为真,则执行其后的语句,否则不执行该语句。其过程为

例:

#include<stdio.h>

void main()
{
    int a,b,max;
    printf("\n input two numbers;");
    scanf("%d%d",&a,&b);
    max=a;
    if(max<b)max=b;
    printf("max=%d",max);
}

2、if-else型

if(表达式) 

  语句1 ;

else

       语句2;  

其过程为:               

 例:

#include<stdio.h>

void main()
{
    int a,b;
    printf("\n input two numbers;");
    scanf("%d%d",&a,&b);
    if(a>b)
        printf("max=%d\n",a);
    else
        printf("max=%d\n",b);
}

3、if-else-if型:前两种形式的if语句一般都用于两个分支的情况。当有多个分支选择时,可采用if-else-if语句,其一般形式为:

if(表达式1)语句1

else if(表达式2)语句2

else if(表达式3)语句3

else if(表达式m)语句m

else 语句 n

在每个语句中,可以有多个语句,但需要加大括号。

具体流程图:

例:

#include<stdio.h>

void main()
{
    char c;
    printf("input a character;");
    c=getchar();
    if(c<32)
    {
        printf("This is a control character\n");
    }
    else if(c>='0'&&c<='9')
    {
        printf("This is a digit\n");
    }
    else if(c>='A'&&c<='z')
    {
        printf("This is a capital letter\n");
    }
    else if(c>='a'&&c<='z')
    { 
        printf("This is a small letter\n");
    }
    else 
    {
        printf("This is an other character\n");
    }
}

猜你喜欢

转载自www.cnblogs.com/lvfengkun/p/10206723.html