雷火电竞-中国电竞赛事及体育赛事平台

歡迎來(lái)到入門(mén)教程網(wǎng)!

C語(yǔ)言

當(dāng)前位置:主頁(yè) > 軟件編程 > C語(yǔ)言 >

C語(yǔ)言菜鳥(niǎo)基礎(chǔ)教程之條件判斷

來(lái)源:本站原創(chuàng)|時(shí)間:2020-01-10|欄目:C語(yǔ)言|點(diǎn)擊:

(一)if...else

先動(dòng)手編寫(xiě)一個(gè)程序

#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;
}

運(yùn)行結(jié)果:

x is not a positive number!

程序分析:

定義一個(gè)整數(shù)x,并給他賦值。這個(gè)值要么大于0,要么不大于0(等于或小于0)。
若是大于0,則打印x is a positive number!
若不大于0,則打印x is not a positive number!

這里建議不要再使用在線(xiàn)編譯器,而是使用本機(jī)編譯器(蘋(píng)果電腦推薦Xcode,PC推薦dev C++)。在本機(jī)編譯器上設(shè)置斷點(diǎn)逐步執(zhí)行,會(huì)發(fā)現(xiàn)if中的printf語(yǔ)句和else中的printf語(yǔ)句只會(huì)執(zhí)行一個(gè)。這是因?yàn)閕f和else是互斥的關(guān)系,不可能都執(zhí)行。

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

稍微改動(dòng)程序

#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;
}

運(yùn)行結(jié)果:

x is zero!

程序分析:
假如條件不止兩種情況,則可用if...else if...else...的句式。
這個(gè)程序里的條件分成三種: 大于0、等于0或小于0。
大于0則打印x is a positive number!
等于0則打印x is zero!
小于0則打印x is a negative number!

注意,x == 0,這里的等號(hào)是兩個(gè),而不是一個(gè)。
C語(yǔ)言中,一個(gè)等號(hào)表示賦值,比如b = 100;
兩個(gè)等號(hào)表示判斷等號(hào)的左右側(cè)是否相等。

(三)多個(gè)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;
}

運(yùn)行結(jié)果:

x belongs to 21~30

程序分析:
(1)
這里把x的值分為好幾個(gè)區(qū)間:(負(fù)無(wú)窮大, 0), [0, 10], [11, 20], [21, 30], [31, 40], (40, 正無(wú)窮大)
(負(fù)無(wú)窮大, 0)用if來(lái)判斷
[0, 10], [11, 20], [21, 30], [31, 40]用else if來(lái)判斷
(40, 正無(wú)窮大)用else來(lái)判斷

(2)
符號(hào)“&&”代表“并且”,表示“&&”左右兩側(cè)的條件都成立時(shí),判斷條件才成立。

上一篇:C語(yǔ)言菜鳥(niǎo)基礎(chǔ)教程之for循環(huán)

欄    目:C語(yǔ)言

下一篇:C++ list的實(shí)例詳解

本文標(biāo)題:C語(yǔ)言菜鳥(niǎo)基礎(chǔ)教程之條件判斷

本文地址:http://www.jygsgssxh.com/a1/Cyuyan/1133.html

網(wǎng)頁(yè)制作CMS教程網(wǎng)絡(luò)編程軟件編程腳本語(yǔ)言數(shù)據(jù)庫(kù)服務(wù)器

如果侵犯了您的權(quán)利,請(qǐng)與我們聯(lián)系,我們將在24小時(shí)內(nèi)進(jìn)行處理、任何非本站因素導(dǎo)致的法律后果,本站均不負(fù)任何責(zé)任。

聯(lián)系QQ:835971066 | 郵箱:835971066#qq.com(#換成@)

Copyright © 2002-2020 腳本教程網(wǎng) 版權(quán)所有