源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

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

  • 时间:2022-01-31 07:30 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:C语言菜鸟基础教程之条件判断
[b](一)if...else[/b] 先动手编写一个程序
#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;
}

运行结果: [code]x is not a positive number![/code] 程序分析: 定义一个整数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是互斥的关系,不可能都执行。 [b](二)if...else if...else[/b] 稍微改动程序
#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;
}

运行结果: [code]x is zero![/code] 程序分析: 假如条件不止两种情况,则可用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; 两个等号表示判断等号的左右侧是否相等。 [b](三)多个else if的使用[/b]
#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;
}

运行结果: [code]x belongs to 21~30[/code] 程序分析: (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) 符号“&&”代表“并且”,表示“&&”左右两侧的条件都成立时,判断条件才成立。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部