对于要先做判断再选择的问题就要使用分支结构
int main()
{
int a = 0, b = 0;
scanf("%d %d", &a, &b);
if (a != b)
{
if (a > b)
{
printf("a>b\n");
}
else
{
printf("a<b\n");
}
}
else
{
printf("a==b\n");
}
return 0;
}
int main()
{
char ch = '\0';
ch = getchar();
if (ch < 32)
{
printf("this is a control character\n");
}
else if (ch >= '0' && ch <= '9')
{
printf("this is a digit character\n");
}
else if (ch >= 'a' && ch <= 'z')
{
printf("this is a small character\n");
}
else if (ch >= 'A' && ch <= 'Z')
{
printf("this is a capital character\n");
}
else
{
printf("this is a other character\n");
}
}
switch是另外一种选择结构的语句,用来代替简单的拥有多个分支的if else语句
switch(整型变量表达式//char short int .....)//不为浮点数,字符串
case常量1(整型)break;//case标签必须是唯一常量值,不允许两个case具有相同常量值
case常量2(整型)break;
int main()
{
char grade = '\0';
printf("input grade(A B C D E )\n");
grade = getchar();
switch (grade)
{
case'A':
case'a':
printf("A(100--90)\n"); break;
case'B':
case'b':
printf("B(90--80)\n"); break;
case'C':
case'c':
printf("C(80--70)\n"); break;
case'D':
case'd':
printf("D(70--60)\n"); break;
case'E':
case'e':
printf("E(<60)\n"); break;
default:
printf("input error\n");
break;
}
return 0;
}
顺次向下执行到break退出
default不是必须的,当没有default时,如果所有的case都匹配失败,那么switch中就什么都不执行,继续执行后续代码。
上面的这种switch被称为有限自动机
一个判断一句话里有多少英文单词的有限状态机
#define begin 0
#define in_word 1
#define out_word 2
#define end 3
int main()
{
char stra[] = { "hello new data is student class" };
int i = 0;
int sum = 0;
int tag = begin;
for (int i = 0; stra[i] != '\0'; i++)
{
switch (tag)
{
case begin:
if (isalpha(stra[i]))
{
tag = in_word;
}
else
{
tag = out_word;
}
break;
case in_word:
if (!isalpha(stra[i]))
{
sum += 1;
tag = out_word;
}
case out_word:
if (isalpha(stra[i]))
{
tag = in_word;
}
break;
}
}
if (tag == in_word)
{
sum += 1;
}
printf("sum:%d\n", sum);
return 0;
}