2021-09-07 C语言学习第五天 (分支和跳转)

C控制语句:分支和跳转

本文主要学习以下内容:

  • 关键字:if 、else 、switch 、continue 、break 、case 、default
  • 运算符:&&、|| 、?:
  • 函数getchar() 、putchar() 、ctype.h系列
  • 如何使用if和if else语句,如何嵌套使用它们
  • 在更复杂的测试表达式中用逻辑运算符组合关系表达式
  • C的条件运算符
  • switch语句
  • break、continue语句
  • 使用C的I/O函数:getchar()和putchar()
  • ctype.h头文件提供的字符分析函数系列

if语句

if语句被称为分支语句或选择语句,因为它相当于一个交叉点,程序要在两条分支中选择一条执行。if的通用形式如下:

if (expression)
	statement

如果对expression求值为真(非零),则执行statement;否则,跳过statement。与while循环一样,statement可以是一条简单语句或复合语句。他们的主要区别是:如果满足条件可执行的话,if语句只能测试和执行一次,而while语句可以测试和执行多次。



if(joe>ron)
{
	joecash++;
	printf("You lose,Ron.\n");
}

if else语句

C提供了可以在两条语句之间做选择的if else语句,其通用形式为:

if(expression)
	statement1
else
	statement2

如果if语句的测试表达式为真,则执行statenent1,如果为假,则执行else后面的statement2。
如果要在if和else之间执行多条语句,必须用花括号把这些语句括起来成为一个块。

if(x>0)
	printf("Incrementing x:\n");
	x++;
else
	printf("x<=0 \n");

x++会被看作一条单独的语句,它不属于if的一部分。

  • 字符输入/输出函数:getchar()和putchar()
    getchar()函数不带任何参数,它从输入队列中返回下一个字符。
ch = getchar();

该语句与下面的语句效果相同:

scanf("%c",&ch);
  • ctype.h系列的字符函数
    C有一系列专门处理字符的函数,这些函数的原型被包含在ctype.h头文件中。这些函数接受一个字符作为参数,如果该字符属于某特殊的类别,就返回一个非零值(真),否则,返回0(假)。
    ctype.h头文件中的字符测试函数
函数名如果是下列参数时,返回值为真
isalnum()字母数字(字母或数字)
isalpha()字母
isblank()标准的空白字符(空格、水平制表符或换行符)
iscntrl()控制字符
isdigit()数字
isgraph()除空格之外的任意可打印字符
islower()小写字母
isprint()可打印字符
ispunct()标点符号
isspace()空白字符
issupper()大写字母
isxdigit()十六进制数字符

ctype.h头文件中的字符映射函数

函数名行为
tolower()如果参数是大写字符,该函数返回小写字符;否则,返回原始参数
toupper()如果参数是小写字符,该函数返回大写字符;否则,返回原始参数

注意:字符映射函数不会修改原始的参数,这些函数只会返回已修改的值。也就是说,下面的语句不改变ch的值:

tolower(ch); //不影响ch的值
ch = tolower(ch);  //这样才会改变ch的值
  • 多重选择else if
if(score<1000)
	bonus = 0;
else if(score < 1500)
	bonus = 1;
else if(score < 2000)
	bonus = 2;
else if(score < 2500)
	bonus = 4;
else
	bonus = 6;

当一个程序中含有多个if 和else时,else会与最近的if匹配

/*多个if else的匹配 */
#include<stdio.h>
int main(void)
{
    int number;

    while(scanf("%d",&number)==1)
    {
        if(number>6)
        if(number<12)
            printf("You are close!\n");
    else
        printf("Sorry,you lose a turn!\n");

    
    }
    return 0;
}

输入的数字和匹配的响应如下:

5
10
You are close!
15
Sorry,you lose a turn!
  • 测试条件中标记的使用
    一直以来,C都习惯用int作为标记的类型,其实新增的_Bool类型更适合。另外,如果在程序中包含了stdbool.h头文件,便可以用bool代替_Bool类型,用true和false分别代替1和0。
/*divisors.c --使用嵌套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 divisible 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;
}

该程序在for循环的测试表达式中使用了逗号运算符,这样每次输入新值时都可以把isPrime设置为true。

Please enter an integer for analysis; Enter q to quit.
12345678
12345678 is divisible by 2 and 6172839.
12345678 is divisible by 3 and 4115226.
12345678 is divisible by 6 and 2057613.
12345678 is divisible by 9 and 1371742.
12345678 is divisible by 18 and 685871.
12345678 is divisible by 47 and 262674.
12345678 is divisible by 94 and 131337.
12345678 is divisible by 141 and 87558.
12345678 is divisible by 282 and 43779.
12345678 is divisible by 423 and 29186.
12345678 is divisible by 846 and 14593.
Please enter another integer for analysis; Enter q to quit.
149
149 is prime.
Please enter another integer for analysis; Enter q to quit.
2013
2013 is divisible by 3 and 671.
2013 is divisible by 11 and 183.
2013 is divisible by 33 and 61.
Please enter another integer for analysis; Enter q to quit.
q
Bye.

逻辑运算符

逻辑运算符含义
&&
||
!
if(ch!='"'&&ch!='\'')
	charcount++;

该if语句的翻译是:如果待测试的字符不是双引号,并且它也不是单引号,那么charcount递增1。

  • 备选拼写:iso646.h头文件
    如果在程序中包含此头文件,便可以使用and代替&&、or代替||、not代替!
if(ch!='"'and ch!='\'')
	charcount++;
传统写法iso646.h
&&and
||or
!not
  • 优先级
    !运算符优先级很高,比乘法运算符还高,与递增运算符优先级相同,只比圆括号优先级低。&&运算符的优先级比||运算符高,但是两者的优先级都比关系运算符低,比赋值运算符高。

条件运算符:?:

C提供条件表达式作为if else语句的一种便捷方式,该表达式使用?:条件运算符。该运算符分为两个部分,需要3个运算对象。条件运算符是C语言中唯一的三元运算符。

x = (y<0)?-y:y;

该语句的意思是“如果y小于0,那么x = -y;否则,x = y”。
典型的例子是,寻找两个变量中的最大值

max = (a > b)?a:b;

如果a大于b,那么将max设置为a;否则,设置为b。

循环辅助:continue和break

  • continue语句:
    三种循环都可以使用continue语句。执行到该语句时,会跳过本次迭代的剩余部分,并开始下一轮迭代。如果continue语句在嵌套循环内,则只会影响包含该语句的内层循环。
for (count = 0;count<10;count++)
{
	ch = getchar();
	if(ch == '\n')
		continue;
	putchar(ch);
}

该例中,执行完continue后,首先递增count,然后将递增后的值和10作比较。

  • break语句
    程序执行到break语句时,会终止包含它的循环,并继续执行下一阶段。同样,如果break语句位于嵌套循环内,他只会影响包含它的当前循环。
/*break.c --使用break退出循环*/
#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后,在执行玩break语句时,程序会直接执行循环后面的第一条语句,连更新部分也跳过。嵌套内层的break只会让程序跳出包含它的当前循环,要跳出外层循环还需要一个break。在上面的程序中,同样还可以用这种方法来控制循环:

while(scanf("%f %f",&length,&width)==2)

多重选择:switch和break

使用if else语句可以很容易编写二选一的程序。然而,有时程序需要在多个选择中做出选择,虽然可以用多个if else来完成,但是使用switch语句更方便。
switch语句的通用形式如下:

switch(number)
{
	case 1:statement 1;
			break;
	case 2:statement 2;
			break;
	case 3:statement 3;
			break;
	default:statement 4;
}
statement 5;

break能让程序离开switch语句,跳转到switch语句的下一条语句(statement 5)。如果没有break语句,就会从匹配标签开始执行到switch末尾。

  • 多重标签
//vowels.c --使用多重标签
#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': e_ct++;
                break;
        case 'i':
        case 'I': i_ct++;
                break;
        case 'o':
        case 'O': o_ct++;
                break;
        case 'u':
        case 'U': u_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;          
}

该程序的运行示例如下:

Enter some text;enter # to quit.
I SEE UNDER THE OVERSEER.#
number of vowels: A    E   I   O   U
                0    7    1    1    1

也可以使用ctype.h系列的toupper()函数来避免使用多重标签。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值