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

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

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

翡翠森林Z   2021-03-29 我要评论
想了解C语言菜鸟基础教程之条件判断的相关内容吗,翡翠森林Z在本文为您仔细讲解C语言基础教程 条件判断的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:C语言基础教程,条件判断,C语言条件判断,C,条件判断,下面大家一起来学习吧。

(一)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 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)
符号“&&”代表“并且”,表示“&&”左右两侧的条件都成立时,判断条件才成立。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们