c控制语句:分支和跳转

来源:互联网 发布:波音市值知乎 编辑:程序博客网 时间:2024/05/22 00:22
一.if语句
#include<stdio.h>
int main(void)
{
    const int FREEZING=0;
    float temperature;
    int cold_days=0;
    int all_days=0;


    printf("Enter the list of daily low temperatures.\n");
    printf("Use Celsius,and enter q to quit.\n");
    while(scanf("%f",&temperature)==1)
    {
        all_days++;
        if(temperature<FREEZING)
   cold_days++;
    }
    if(all_days!=0)
        printf("%d days total: %.1f %% were below freezing.


\n",all_days,100.0*(float)cold_days/all_days);
    if(all_days==0)
        printf("No data entered!\n");
    return 0;
}


这个程序是一个简单的循环和分支语句。程序读入一系列每日的最低温度,并报


告输入的总数,以及最低温度在零度下的天数的百分比。
if语句被称为分支语句或者选择语句。一般形式为:
if(expression)
      statement
如果expression为真就执行statement,否则就跳过该语句。
二.在if语句中添加else关键字
简单形式的if语句可以使我们选择执行一条语句,我们还可以通过使用if else形


式在两个语句间做出选择。
1.getchar()和putchar()
我们可以使用getchar()和putchar()来读写字符。这两个函数仅仅处理字符,所


以比printf()和scanf()更快更简洁。
ch=getchar;
putchar(char);
#include<stdio.h>
#define SPACE ' '
int main(void)
{
    char ch;


    ch=getchar();
    while(ch!='\n')
    {
        if(ch==SPACE)
  putchar(ch);
else
  putchar(ch+1);
  ch=getchar();
    }
    putchar(ch);
    return 0;
}


这个循环和上面那个比较,上面那个用scanf()返回状态而不是输入元素的值来决


定何时终止,而这个程序是由输入程序元素本身的值决定何时终止循环。
为了体现c的编程风格下面程序
ch=getchar();
while(ch!='\n')
{


}
可以用下面程序代替
while((ch=getchar())!='\n')
{


}
在这个例子中字符实际上是作为整数本存储的。
2.ctype.h字符函数
ANSI C有一些标准的函数来分析字符,判断字符是否为空格,逗号等等。ctype.h


头文件包含了这些函数的原型。这些函数接受一个字符作为参数,如果该字符属


于某特定的种类就返回真,否则就为假。如果isalpha()函数的参数是个字母,


则它返回一个非零值。
#include<stdio.h>
#include<ctype.h>
int main(void)
{
    char ch;


     while((ch=getchar())!='\n')
     {
         if(isalpha(ch))
    putchar(ch+1);
else 
    putchar(ch);


     }
     putchar(ch);
     return 0;
}


如果需要更多函数,可以查表。
3.多重选择else if
日常生活经常会给我们提供两个以上的选择,可以使用else if扩展if else结构


来适应需求。#include<stdio.h>
#define RATE1 0.12589
#define RATE2 0.17901
#define RATE3 0.20971
#define BREAK1 360.0
#define BREAK2 680.0
#define BASE1 (RATE1*BREAK1)
#define BASE2 (BASE1+(RATE2*(BREAK2-BREAK1)))


int main(void)
{
    double kwh;
    double bill;


    printf("Please enter the kwh used.\n");
    scanf("%lf",&kwh);
    if(kwh<=BREAK1)
        bill=RATE1*kwh;
    else if(kwh<=BREAK2)
        bill=BASE1+(RATE2*(kwh-BREAK1));
    else 
        bill=BASE2+(RATE3*(kwh-BREAK2));
    printf("The charge for %.1f kwh is $%1.2f.\n",kwh,bill);
    return 0;
}


多重选择语句的嵌套,c99中最多运行127层嵌套。
在多重嵌套中,如果没有花括号指明,else与和它最接近的一个if相匹配。
#include<stdio.h>
#include<stdbool.h>
int main(void)
{
    unsigned long num;
    unsigned long div;
    bool isPrime;
    
    printf("Please enter an integer for analysis:");
    printf("Enter q to quit.\n");
    while(scanf("%lu",&num)==1)
    {
        for(div=2,isPrime=true;(div*div)<=num;div++)
{
   if(num%div==0)
   {
       if((div*div)!=num)
   printf("%lu is divisible by %lu and %lu.


\n",num,div,num/div);
   else 
       printf("%lu is divisble by %lu.\n",num,div);
           isPrime=false;
   }
}
if(isPrime)
   printf("%lu is prime.\n",num);
printf("Please enter another integer for analysis:");
printf("Enter q to quit.\n");
    }
    printf("Bye.\n");
    return 0;
}


这个程序是判断一个数是否为素数,如果不是则写出它的约数。
三.获得逻辑性
两个或者多个关系符组合起来有很多用处。
#include<stdio.h>
#define PERIOR '.'
int main(void)
{
    int ch;
    int charcount=0;


    while((ch=getchar())!=PERIOR)
    {
        if(ch!='"'&&ch!='\'')
   charcount++;
    }
    printf("There are %d non-quote characters.\n",charcount);
    return 0;
}


这个一个程序,用来计算一个输入语句中除单引号和双引号以外有多少个字符,


用“.”来标识一个句子结束。
改变拼写法:iso646.h
在iso646的头文件中定义了可以替代的文件,可以用and代替&&,用or代替||,用


not代替!。
四.一个统计字数的程序
#include<stdio.h>
#include<ctype.h>
#include<stdbool.h>
#define STOP '|'
int main(void)
{
    char c;
    char prev;
    long n_chars=0l;
    int n_lines=0;
    int n_words=0;
    int p_lines=0;
    bool inword=false;


    printf("Enter text to be analyzed(| to terminate): \n");
    prev='\n';
    while((c=getchar())!=STOP)
    {
        n_chars++;
if(c=='\n')
   n_lines++;
if(!isspace(c)&&!inword)
{
   inword=true;
   n_words++;
}
if(isspace(c)&&inword)
   inword=false;
prev=c;
    }
    if(prev!='\n')
        p_lines=1;
    printf("characters=%ld,word=%d,lines=%d",n_chars,n_words,n_lines);
    printf("partial lines=%d\n",p_lines);
    return 0;
}


上面是一个统计字数的程序,其中STOP代表通知输入结束的ch取值。使用ctype.h


中的isspace()函数会更简单,如果该函数的参数是空白字符,它返回真。
五.条件运算符?:
c提供一种简写方式来表示if else语句的一种形式,这被称为条件表达式,并使


用条件运算符(?:)。一般形式:
expression1?expression2:expression3
如果expression1为真(非零),整个条件表达式的值和expression2的值相同。


如果expression1位假(零),整个条件表达式的值等于expression3的值。
#include<stdio.h>
#define COVERAGE 200
int main(void)
{
    int sq_feet;
    int cans;


    printf("Enter number of square feet to be painted:\n");
    while(scanf("%d",&sq_feet)==1)
    {
        cans=sq_feet/COVERAGE;
cans+=((sq_feet%COVERAGE==0))?0:1;
printf("You need %d %s of paint.\n",cans,cans==1?"can":"cans");
printf("Enter next value (q to quit):\n");
    }
    return 0;
}


这个程序计算向给定的平方英尺的面积涂油漆,全部涂完需要多少油漆。
六.循环辅助手段:continue和break
一般来说,进入循环体以后,在下次循环判断之前程序执行循环体中的所有语句


。continue和break语句使你可以根据循环体内进行的判断结果来忽略部分循环甚


至终止它。
#include<stdio.h>
int main(void)
{
    const float MIN=0.0f;
    const float MAX=100.0f;


    float score;
    float total=0.0f;
    int n=0;
    float min=MAX;
    float max=MIN;


    printf("Enter the first score(q to quit):");
    while(scanf("%f",&score)==1)
    {
        if(score<MIN||score>MAX)
{
   printf("%0.1f is an invalid value.Try again:",score);
   continue;
}
printf("Accepting %0.1f:\n",score);
min=(score<min)?score:min;
max=(score>max)?score:max;
total+=score;
n++;
printf("Enter next score(q to quit):");
    }
    if(n>0)
    {
        printf("Average of %d scores is %0.1f.\n",n,total/n);
printf("Low=%0.1f,high=%0.1f\n",min,max);
    }
    else
        printf("No valid scores were entered.\n");
    return 0;
}




continue可结束当前循环,适当使用continue可以简化程序。
#include<stdio.h>
int main(void)
{
    float length,width;


    printf("Enter the length of the rectangle:\n");
    while(scanf("%f",&length)==1)
    {
        printf("Length=%0.2f: \n",length);
printf("Enter its width:\n");
if(scanf("%f",&width)!=1)
   break;
printf("Width=%0.2f:\n",width);
printf("Area=%0.2f:\n",length*width);
printf("Enter the length of the rectangle:\n");
    }
    printf("Done.\n");
    return 0;
}


break不同于continue,它可以直接退出循环。它实际上是switch的附属物。
七.多重选择:switch和break
当程序需要多重选择时,我们可以使用if else if else来做,但是我们一般还是


使用c的switch语句更加方便。
#include<stdio.h>
#include<ctype.h>
int main(void)
{
    char ch;
    printf("Give me a letter of the alphabet,and I will give");
    printf("an animal name\nbeginning with that letter.\n");
    printf("Please type in a letter:type # to end my act.\n"):
    while((ch=getchar())!='#')
    {
     if('\n'==ch)
        continue;
     if(islower(ch))
         switch(ch)
         {
            case 'a':
                printf("argail,a wild sheep of Asia\n");
                break;
            case 'b':
                printf("babirusa,a wild pig of Malay\n");
                break;
            case 'c':
                printf("coati,racoonlike mammal\n");
                break;
            case 'd':
                printf("desman,aquatic,molelike critter\n");
                break;
            case 'e':
                printf("echidna,the spiny anteater\n");
                break;
            case 'f':
                printf("fisher,brownish marten\n");
                break;
            default:
                  printf("That is a stumper!\n");
          }
        else
            printf("I recognize only lowercase letters.\n");
        while(getchar()!='\n')
            continue;
           printf("Please type another letter or a #.\n");
     }
     printf("Bye!\n");
     return 0;
}


本程序的两个主要特点是switch语句的使用和输入处理。
break语句用于循环和switch中,而continue仅用于循环。
#include<stdio.h>
int main(void)
{
    char ch;
    int a_ct,e_ct,i_ct,o_ct,u_ct;
    a_ct=e_ct=i_ct=o_ct=u_ct=0;
    printf("Enter some text:enter # to quit.\n");
    while((ch=getchar())!='#')
    {
        switch(ch)
        {
             case 'a':
             case 'A':a_ct++;
                      break;
             case 'e':
             case 'E':a_ct++;
                      break;
             case 'i':
             case 'I':a_ct++;
                      break;
             case 'o':
             case 'O':a_ct++;
                      break;
             case 'u':
             case 'U':a_ct++;
                      break; 
              default:break;


         }
    }
    printf("number of vowels:A    E    I   O   U\n");
    printf("                 %4d %4d %4d %4d  %4d


\n",a_ct,e_ct,i_ct,o_ct,u_ct);
    return 0;
}
本程序是多重标签。假定ch是字母i,则switch语句定位到标签为case‘i’的位


置,因为没有break同该标签相关联,所以程序流程继续前进到下一个语句,即


i_ct++。如果ch是I,程序流程就直接定位到那条语句。本质上,两个标签都指向


相同的语句。
在这个特例中,可以通过使用ctype.h系列中的toupper()函数在进行判断之前


将所有的字母转换大写字母来避免多重标签。
八.goto语句
goto语句包括两个部分:goto和一个标签名称。标签的命名遵循与命名变量条件


相同的约定,如下所示:
goto parts
为了使上述语句工作,函数必须包含由part2标签定位的其他语句。
part2:printf("Refined analysis:\n")
在c中尽量少使用goto语句或者不使用goto语句。
0 0
原创粉丝点击