您的位置:首页 > 其它

C控制语句:分支与跳转

2014-11-11 16:57 375 查看
1.前导程序

使用break语句跳出循环
//使用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语句跳出循环
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\n");
printf("beginning with that letter.\n");
printf("Please type in a letter:type # to end my cat.\n");
while((ch=getchar())!='#')
{
if('\n'==ch)
continue;
if(islower(ch))
switch(ch)
{
case 'a':
printf("argali,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's a stumper!\n");
}//switch语句结束。
else
printf("I recognize only lowercase letters.\n");
while(getchar()!='\n')
continue;//跳过输入行的剩余部分
printf("please type another letter or a #.\n");
}//while循环结束
printf("Bye!\n");
return 0;
}


紧跟在switch后圆括号里的表达式被求值,然后程序扫描标签列表,直到搜索到一个与该值相匹配的标签。

如果没有break语句,从相匹配的标签到switch末尾的每条语句都将被处理。

圆括号中的switch判断表达式应该具有整数值(包括char类型),不能用变量作为case标签。

可以对一个给定的语句使用多重case标签。

8.goto语句

应该避免goto语句,具有讽刺意味的是,C不需要goto,却有一个比大多数语言更好的goto,它允许在标签中使用描述性的标签而不仅仅是数字。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: