• 周六. 5月 3rd, 2025

C语言入门 — if else

2月 15, 2020

C语言入门简单条件判断语句,if else, 本文章会使用到《C语言入门 — 函数接口

1、if else 可以简单的理解为“如果 就 否则”的语句,下面以举例子来进行解释,使用if else 判断两个整数的大小。

#include <stdio.h>
int max(int a, int b)
{
    int c;
    if(a>b)
    {
        printf("a=%d\n",a);
        printf("b=%d\n",b);
        printf("a>b\n");
        c = a;
    }else{
        printf("a=%d\n",a);
        printf("b=%d\n",b);
        printf("a<=b\n");
        c = b;
    }
    return c;
}

int main(void)
{
    printf("max1:%d\n",max(5,3));
    printf("max2:%d\n",max(5,6));
    return 0;
}

运行结果:

a=5
b=3
a>b
max1:5
a=5
b=6
a<=b
max2:6

 2、if else的进阶版,if else if else 举例说明, 使用if else if else来判断大于 等于 小于

#include <stdio.h>
int max(int a, int b)
{
    int c;
    if(a>b)
    {
        printf("a=%d\n",a);
        printf("b=%d\n",b);
        printf("a>b\n");
        c = a;
    }else if(a == b){
        printf("a=%d\n",a);
        printf("b=%d\n",b);
        printf("a==b\n");
        c = b;
    }else{
        printf("a=%d\n",a);
        printf("b=%d\n",b);
        printf("a<b\n");
        c = b;
    }
    return c;
}

int main(void)
{
    printf("max1:%d\n",max(5,3));
    printf("max2:%d\n",max(5,5));
    printf("max3:%d\n",max(5,6));
    return 0;
}

运行结果:

a=5
b=3
a>b
max1:5
a=5
b=5
a==b
max2:5
a=5
b=6
a<b
max3:6