﻿ C语言菜鸟基础教程之条件判断 - 鸿网互联

# C语言菜鸟基础教程之条件判断

（一）if...else 先动手编写一个程序 #include stdio.hint main(){ int x = -1; if(x 0) { printf("x is a positive number!\n"); } else { printf("x is not a positive number!\n"); } return 0;} 运行结果： x is not a positive number! 程序分析： 定义

（一）if...else

```#include <stdio.h>

int main()
{
int x = -1;
if(x > 0)
{
printf("x is a positive number!\n");
}
else
{
printf("x is not a positive number!\n");
}

return 0;
}

```

`x is not a positive number!`

（二）if...else if...else

```#include <stdio.h>

int main()
{
int x = 0;
if(x > 0)
{
printf("x is a positive number!\n");
}
else if(x == 0)
{
printf("x is zero!\n");
}
else
{
printf("x is a negative number!\n");
}

return 0;
}

```

`x is zero!`

C语言中，一个等号表示赋值，比如b = 100；

（三）多个else if的使用

```#include <stdio.h>

int main()
{
int x = 25;
if(x < 0)
{
printf("x is less than 0\n");
}
if(x >= 0 && x <= 10)
{
printf("x belongs to 0~10\n");
}
else if(x >= 11 && x <= 20)
{
printf("x belongs to 11~20\n");
}
else if(x >= 21 && x <= 30)
{
printf("x belongs to 21~30\n");
}
else if(x >= 31 && x <= 40)
{
printf("x belongs to 31~40\n");
}
else
{
printf("x is greater than 40\n");
}

return 0;
}

```

`x belongs to 21~30`

（1）

（负无穷大, 0）用if来判断
[0, 10], [11, 20], [21, 30], [31, 40]用else if来判断
(40, 正无穷大)用else来判断

（2）

<