C语言之分支

来源:互联网 发布:成都美工平均工资 编辑:程序博客网 时间:2024/04/30 14:05

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等于true15 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       statement13 else4       statement25 //如果希望在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     else36         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         else39             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,它允许在标签中使用描述性的标签而不仅仅是数字
0 0
原创粉丝点击