加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 创业 > C语言 > 正文

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

发布时间:2020-12-15 03:36:13 所属栏目: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!

程序分析:

定义一个整数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

稍微改动程序

#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的使用

#include <stdio.h>

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

运行结果:

x belongs to 21~30

程序分析:
(1)
这里把x的值分为好几个区间:(负无穷大,0),[0,10],[11,20],[21,30],[31,40],(40,正无穷大)
(负无穷大,0)用if来判断
[0,40]用else if来判断
(40,正无穷大)用else来判断

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读