C語言之分支

1.前導程序

複製代碼
 1 //統計字符、單詞和行
 2 #include<stdio.h>
 3 #include<ctype.h>        //爲isspace()提供函數原型
 4 #include<stdbool.h>        //爲bool、true和flase提供定義
 5 #define  STOP  '|'
 6 int main(void)
 7 {
 8     char c;                //讀入字符
 9     char prev;            //前一個讀入字符
10     long n_chars=0L;    //字符數
11     int n_lines=0;        //行數
12     int n_words=0;        //單詞數
13     int p_lines=0;        //不完整的行數
14     bool inword=false;    //如果C在一個單詞中,則 inword等於true
15 
16     printf("Enter text to be analyzed(| to terminate):\n");
17     prev='\n';            //用於識別完整的行
18     while((c=getchar())!=STOP)
19     {
20         n_chars++;        //統計字符
21         if(c=='\n')
22             n_lines++;    //統計行
23         if(!isspace(c)&&!=inword)
24         {
25             inword=true;    //開始一個新單詞
26             n_words++;        //統計單詞
27         }
28         if(isspace(c)&&inword)
29             inword=false;    //到達單詞的結尾
30         prev=c;                //保存字符值
31     }
32 
33     if(prev!='\n')
34         p_lines=true;
35     printf("characters=%ld,words=%d,lines=%d,",
36             n_chars,n_words,n_lines);
37     printf("partial lines=%d\n",p_lines);
38     return 0;
39 }
複製代碼

2.If語句

  • 在If語句中,判斷和執行(如果可能的話)僅有一次,而在while循環中,判斷和執行可以重複多次。
  • 判斷語句通常是一個關係表達式,表達式的值爲0就視爲假,忽略該語句。
複製代碼
 1 //求出溫度低於零度的天數的百分比
 2 #include<stdio.h>
 3 int main(void)
 4 {
 5     const int FREEZING=0;
 6     float temperature;
 7     int cold_days=0;
 8     int all_days=0;//初始化天氣溫度輸入總天數
 9 
10     printf("Enter the list of daily low temperatures.\n");
11     printf("Use Celsius,and enter q to quit.\n");
12     while(scanf("%f",&temperature)==1)//有正確輸入則進入循環
13     {
14         all_days++;
15         if(temperature<FREEZING)
16             cold_days++;//零度以下溫度天數計數器
17     }
18     if(all_days!=0)
19         printf("%d days total:%.1f%% were below freezing.\n",
20             all_days,100.0*(float)cold_days/all_days);
21     if(all_days==0)
22         printf("No data entered!\n");
23     return 0;
24 }
複製代碼

3.在If 語句中添加else關鍵字

複製代碼
1 if(expression)
2       statement1
3 else
4       statement2
5 //如果希望在if和else之間有多條語句,則必須用於{}
 
複製代碼
  • ch=getchar();  ==  scanf("%c",&ch);
  • ch=putchar();  ==  printf("%c",ch);//他們不需要格式說明符,因爲他們只對字符起作用
  • 字符實際上是作爲整數被存儲的。
  • c風格:while((ch=getchar())!='\n')  //ch不等於換行符。
改變輸入,只保留其中的空格
  • 在多重選擇else if語句中,如果沒有花括號指明,則else和它最接近的if配對,編譯器是忽略編排的。#顯示一個數的約數!<stdbool.h>

4.獲得邏輯性

  • (exp1  && exp2)  運算符“與”,當兩個關係表達式都爲真的時候爲真。
  • (exp1  ||  exp2)   運算符“或”,當兩個表達式中至少一個爲真時爲真。
  • (!q)                    運算符“非”。
  • 優先級:最好使用().邏輯表達式從左到右求值,一旦發現有使表達式爲假的因素,立即停止求值。
  • if(10<=n<=30)  //請不要這樣書寫表達式,該代碼是個語義錯誤不是語法錯誤,所以編譯器並不會捕獲它。

5.條件運算符?:(唯一一個 三元運算符)

  • 這個運算符帶着三個操作數,每個操作數都是一個表達式 。
  • expression1 ? expression 2:expression 3  //如果1爲真,整個表達式的值爲2,否則爲3.
複製代碼
 1 //使用條件運算符
 2 #include<stdio.h>
 3 #define CONVERACE  200
 4 int main(void)
 5 {
 6     int sq_feet;
 7     int cans;
 8 
 9     printf("Enter number of square feet to be painted:\n");
10     while(scanf("%d",&sq_feet)==1)
11     {
12         cans=sq_feet/CONVERACE;
13         cans+=((sq_feet%CONVERACE==0))?0:1;
14         printf("You need %d %s of print.\n",cans,cans==1?"can":"cans");
15         printf("Enter next value(q to quit):\n");
16     }
17     return 0;
18 }
複製代碼

 6.循環輔助手段continue和break

(1)continue適用於三種循環模式,當運行到該語句時它導致剩下的迭代部分被忽略,開始下一次迭代。可以再主語句中消除一級縮排,還可以作爲佔位符。

while((ch=getchar())!='\n')

{   if(ch=='\t')

continue;

putchar(ch);

}//該循環跳過製表符,並且僅當遇到換行符時退出。

 

複製代碼
 1 //使用continue跳過部分循環
 2 //程序接受輸入一系列數字,然後輸出最小值和最大值
 3 #include<stdio.h>
 4 int main(void)
 5 {
 6     const float MIN=0.0f;
 7     const float MAX=100.0f;
 8 
 9     float score;
10     float total=0.0f;
11     int n=0;
12     float min=MAX;
13     float max=MIN;
14 
15     printf("Enter the first score(q to quit):");
16     while(scanf("%f",&score)==1)
17     {
18         if(score<MIN||score>MAX)
19         {
20             printf("%0.1f is an invalid value,try again:",score);
21             continue;
22         }
23         printf("Accepting %0.1f:\n",score);
24         min=(score<min)?score:min;
25         max=(score>max)?score:max;
26         total+=score;
27         n++;
28         printf("Enter next score (q to quit):");
29     }
30     if(n>0)
31     {
32         printf("Average of %d scores is %0.1f.\n",n,total/n);
33         printf("Low=%0.1f,high=%0.1f\n",min,max);
34     }
35     else
36         printf("No valid scores were entered.\n");
37     return 0;
38 }
複製代碼

(2)break語句導致程序終止包含它的循環,並進行程序的下一階段。break語句使程序轉到緊接着該循環後的第一天語句去執行,在for循環中,與continue不同,控制段的更新部分也將被跳過,嵌套循環中的break語句只是使程序跳出了裏層的循環,要跳出外層的循環則需要另外的break語句。

使用break語句跳出循環

7.多重選擇:switch和break

複製代碼
 1 //使用swithch語句
 2 #include<stdio.h>
 3 #include<ctype.h>
 4 int main(void)
 5 {
 6     char ch;
 7     printf("Give me a letter of the alphabet,and I will give an animal name\n");
 8     printf("beginning with that letter.\n");
 9     printf("Please type in a letter:type # to end my cat.\n");
10     while((ch=getchar())!='#')
11     {
12         if('\n'==ch)
13             continue;
14         if(islower(ch))
15             switch(ch)
16             {
17             case 'a':
18                 printf("argali,a wild sheep of Asia\n");
19                 break;
20             case 'b':
21                 printf("babirusa, a wild pig of Malay\n");
22                 break;
23             case 'c':
24                 printf("coati,racoonlike mammal\n");
25                 break;
26             case 'd':
27                 printf("desman,aquatic,molelike critter\n");
28                 break;
29             case 'e':
30                 printf("echidna,the spiny anteater\n");
31                 break;
32             case 'f':
33                 printf("fisher,brownish marten\n");
34                 break;
35             default:
36                 printf("That's a stumper!\n");
37         }//switch語句結束。
38         else
39             printf("I recognize only lowercase letters.\n");
40         while(getchar()!='\n')
41             continue;//跳過輸入行的剩餘部分
42         printf("please type another letter or a #.\n");
43     }//while循環結束
44     printf("Bye!\n");
45     return 0;
46 }
複製代碼
  • 緊跟在switch後圓括號裏的表達式被求值,然後程序掃描標籤列表,直到搜索到一個與該值相匹配的標籤。
  • 如果沒有break語句,從相匹配的標籤到switch末尾的每條語句都將被處理。
  • 圓括號中的switch判斷表達式應該具有整數值(包括char類型),不能用變量作爲case標籤。
  • 可以對一個給定的語句使用多重case標籤。

8.goto語句

  • 應該避免goto語句,具有諷刺意味的是,C不需要goto,卻有一個比大多數語言更好的goto,它允許在標籤中使用描述性的標籤而不僅僅是數字
發佈了67 篇原創文章 · 獲贊 0 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章