C控制语句:分支与跳转

1.前导程序

//统计字符、单词和行
#include<stdio.h>
#include<ctype.h>        //为isspace()提供函数原型
#include<stdbool.h>        //为bool、true和flase提供定义
#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;    //如果C在一个单词中,则 inword等于true

    printf("Enter text to be analyzed(| to terminate):
");
    prev='
';            //用于识别完整的行
    while((c=getchar())!=STOP)
    {
        n_chars++;        //统计字符
        if(c=='
')
            n_lines++;    //统计行
        if(!isspace(c)&&!=inword)
        {
            inword=true;    //开始一个新单词
            n_words++;        //统计单词
        }
        if(isspace(c)&&inword)
            inword=false;    //到达单词的结尾
        prev=c;                //保存字符值
    }

    if(prev!='
')
        p_lines=true;
    printf("characters=%ld,words=%d,lines=%d,",
            n_chars,n_words,n_lines);
    printf("partial lines=%d
",p_lines);
    return 0;
}
统计字符、单词和行

2.If语句

  • 在If语句中,判断和执行(如果可能的话)仅有一次,而在while循环中,判断和执行可以重复多次。
  • 判断语句通常是一个关系表达式,表达式的值为0就视为假,忽略该语句。
求出温度低于零度的天数的百分比
//求出温度低于零度的天数的百分比
#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.
");
    printf("Use Celsius,and enter q to quit.
");
    while(scanf("%f",&temperature)==1)//有正确输入则进入循环
    {
        all_days++;
        if(temperature<FREEZING)
            cold_days++;//零度以下温度天数计数器
    }
    if(all_days!=0)
        printf("%d days total:%.1f%% were below freezing.
",
            all_days,100.0*(float)cold_days/all_days);
    if(all_days==0)
        printf("No data entered!
");
    return 0;
}
求出温度低于零度的天数的百分比

3.在If 语句中添加else关键字

if(expression)
      statement1
else
      statement2
//如果希望在if和else之间有多条语句,则必须用于{}
  • ch=getchar();  ==  scanf("%c",&ch);
  • ch=putchar();  ==  printf("%c",ch);//他们不需要格式说明符,因为他们只对字符起作用
  • 字符实际上是作为整数被存储的。
  • c风格:while((ch=getchar())!=' ')  //ch不等于换行符。
改变输入,只保留其中的空格
//改变输入,只保留其中的空格
//getchar()和putchar()只对字符起作用,不需要格式说明符
#include<stdio.h>
#define   SPACE  ' '
int main(void)
{
    char ch;

    ch=getchar();        //读取一个字符
    while(ch!='
')        //当一行未结束时
    {
        if(ch==SPACE)   //空格的时候不变
            putchar(ch);//不改变这个字符
        else
            putchar(ch+1);    //改变其他字符
            ch=getchar();//获取下一个字符
    }
        
    putchar(ch);        //打印换行字符
    return 0;
}
改变输入,只保留其中的空格
  • 在多重选择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.
//使用条件运算符
#include<stdio.h>
#define CONVERACE  200
int main(void)
{
    int sq_feet;
    int cans;

    printf("Enter number of square feet to be painted:
");
    while(scanf("%d",&sq_feet)==1)
    {
        cans=sq_feet/CONVERACE;
        cans+=((sq_feet%CONVERACE==0))?0:1;
        printf("You need %d %s of print.
",cans,cans==1?"can":"cans");
        printf("Enter next value(q to quit):
");
    }
    return 0;
}
使用条件运算符

 6.循环辅助手段continue和break

(1)continue适用于三种循环模式,当运行到该语句时它导致剩下的迭代部分被忽略,开始下一次迭代。可以再主语句中消除一级缩排,还可以作为占位符。

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

{   if(ch==' ')

continue;

putchar(ch);

}//该循环跳过制表符,并且仅当遇到换行符时退出。

//使用continue跳过部分循环
//程序接受输入一系列数字,然后输出最小值和最大值
#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:
",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,total/n);
        printf("Low=%0.1f,high=%0.1f
",min,max);
    }
    else
        printf("No valid scores were entered.
");
    return 0;
}
使用continue跳过部分循环

(2)break语句导致程序终止包含它的循环,并进行程序的下一阶段。break语句使程序转到紧接着该循环后的第一天语句去执行,在for循环中,与continue不同,控制段的更新部分也将被跳过,嵌套循环中的break语句只是使程序跳出了里层的循环,要跳出外层的循环则需要另外的break语句。

使用break语句跳出循环
//使用break语句跳出循环
#include<stdio.h>
int main(void)
{
    float length,width;

    printf("Enter the length of the rectangle:
");
    while(scanf("%f",&length)==1)
    {
        printf("Length=%0.2f:
",length);
        printf("Enter its 
");
        if(scanf("%f",&width)!=1)//导致程序终止包含它的循环,并进行程序的下一阶段
            break;
        printf("Width=%0.2f:
",width);
        printf("Area=%0.2f:
",length*width);
        printf("Enter the length of the rectangle:
");
    }
    printf("Done.
");
    return 0;
}
使用break语句跳出循环

7.多重选择:switch和break

使用swithch语句
//使用swithch语句
#include<stdio.h>
#include<ctype.h>
int main(void)
{
    char ch;
    printf("Give me a letter of the alphabet,and I will give an animal name
");
    printf("beginning with that letter.
");
    printf("Please type in a letter:type # to end my cat.
");
    while((ch=getchar())!='#')
    {
        if('
'==ch)
            continue;
        if(islower(ch))
            switch(ch)
            {
            case 'a':
                printf("argali,a wild sheep of Asia
");
                break;
            case 'b':
                printf("babirusa, a wild pig of Malay
");
                break;
            case 'c':
                printf("coati,racoonlike mammal
");
                break;
            case 'd':
                printf("desman,aquatic,molelike critter
");
                break;
            case 'e':
                printf("echidna,the spiny anteater
");
                break;
            case 'f':
                printf("fisher,brownish marten
");
                break;
            default:
                printf("That's a stumper!
");
        }//switch语句结束。
        else
            printf("I recognize only lowercase letters.
");
        while(getchar()!='
')
            continue;//跳过输入行的剩余部分
        printf("please type another letter or a #.
");
    }//while循环结束
    printf("Bye!
");
    return 0;
}
  • 紧跟在switch后圆括号里的表达式被求值,然后程序扫描标签列表,直到搜索到一个与该值相匹配的标签。
  • 如果没有break语句,从相匹配的标签到switch末尾的每条语句都将被处理。
  • 圆括号中的switch判断表达式应该具有整数值(包括char类型),不能用变量作为case标签。
  • 可以对一个给定的语句使用多重case标签。

8.goto语句

  • 应该避免goto语句,具有讽刺意味的是,C不需要goto,却有一个比大多数语言更好的goto,它允许在标签中使用描述性的标签而不仅仅是数字。
原文地址:https://www.cnblogs.com/dondre/p/4089952.html