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

时间:2022-04-05 07:34:36

(一)if...else

先动手编写一个程序

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#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!

程序分析:

定义一个整数x,并给他赋值。这个值要么大于0,要么不大于0(等于或小于0)。
若是大于0,则打印x is a positive number!
若不大于0,则打印x is not a positive number!

这里建议不要再使用在线编译器,而是使用本机编译器(苹果电脑推荐Xcode,PC推荐dev C++)。在本机编译器上设置断点逐步执行,会发现if中的printf语句和else中的printf语句只会执行一个。这是因为if和else是互斥的关系,不可能都执行。

(二)if...else if...else

稍微改动程序

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#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!

程序分析:
假如条件不止两种情况,则可用if...else if...else...的句式。
这个程序里的条件分成三种: 大于0、等于0或小于0。
大于0则打印x is a positive number!
等于0则打印x is zero!
小于0则打印x is a negative number!

注意,x == 0,这里的等号是两个,而不是一个。
C语言中,一个等号表示赋值,比如b = 100;
两个等号表示判断等号的左右侧是否相等。

(三)多个else if的使用

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#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)
这里把x的值分为好几个区间:(负无穷大, 0), [0, 10], [11, 20], [21, 30], [31, 40], (40, 正无穷大)
(负无穷大, 0)用if来判断
[0, 10], [11, 20], [21, 30], [31, 40]用else if来判断
(40, 正无穷大)用else来判断

(2)
符号“&&”代表“并且”,表示“&&”左右两侧的条件都成立时,判断条件才成立。

原文链接:http://www.jianshu.com/p/6e9fb5a9c5b7