C语言基础语法学习笔记——流程控制
发布时间:2023-02-10 22:50:19 177
相关标签:
NS图、流程图
分类
顺序:语句逐句执行 选择:出现了一种以上的情况 循环:在某个条件成立的情况下,重复执行某个动作
关键字
选择:if-else switch-case 循环:while do-while for if-goto 辅助控制:continue break
1、选择语句if-else
格式:
if (exp)
cmd;
if (exp)
cmd1;
else
cmd2;
注意:else只与最近的if匹配,与缩进无关
#include
int main(void)
{
int a = 1, b = 1, c = 2;
if (a == b)
if (b == c)
printf("a == b == c\n");
else
printf("a != b\n"); // a != b
if (a == b)
{
if (b == c)
printf("a == b == c\n");
}
else
printf("a != b\n");
return 0;
}
#include
int main(void)
{
int score, res;
while (1)
{
printf("Enter a score[0,100]: ");
res = scanf("%d", &score);
if (res <= 0) break;
if (score < 0 || score > 100)
{
fprintf(stderr, "Bad input\n");
break;
}
if (score >=90 && score <= 100)
puts("A");
else if (score >=80 && score < 90)
puts("B");
else if (score >= 70 && score < 80)
puts("C");
else if (score >= 60 && score < 70)
puts("D");
else if (score >= 0 && score < 60)
puts("E");
}
return 0;
}
2、选择语句switch-case
格式:
switch (exp)
{
case 常量或常量表达式:
break;
case 常量或常量表达式:
break;
deault:
;
}
#include
int main(void)
{
int score, res;
while (1)
{
printf("Please enter a score: ");
res = scanf("%d", &score);
if (res <= 0) break;
if (score < 0 || score > 100)
{
fprintf(stderr, "EINVAL\n");
break;
}
switch (score / 10)
{
case 10:
case 9:
puts("A");
break;
case 8:
puts("B");
break;
case 7:
puts("C");
break;
case 6:
puts("D");
break;
case 5:
case 4:
case 3:
case 2:
case 1:
case 0:
puts("E");
break;
default:
fprintf(stderr, "Unknown\n");
break;
}
}
return 0;
}
#include
int main(void)
{
int ch;
ch = getchar();
switch (ch)
{
case 'a':
case 'A':
puts("Ant: a very small insect that lives under the ground in large and well-organized social groups.");
break;
case 'b':
case 'B':
puts("Butterfly: a type of insect with large, often brightly coloured wings");
break;
case 'c':
case 'C':
puts("Cobra: a poisonous snake from Africa and southern Asia that makes itself look bigger and more threatening by spreading the skin at the back of its head");
break;
case 'd':
case 'D':
puts("Donkey: an animal like a small horse with long ears");
break;
default:
fprintf(stderr, "EINVAL\n");
break;
}
return 0;
}
文章来源: https://blog.51cto.com/u_15789322/5786110
特别声明:以上内容(图片及文字)均为互联网收集或者用户上传发布,本站仅提供信息存储服务!如有侵权或有涉及法律问题请联系我们。
举报