1

【C语言_9】快速掌握分支结构!

 1 year ago
source link: https://blog.51cto.com/u_15420562/5723639
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

1.分支结构的标准公式

//单条语句
if(测试条件)
条件为真所执行的语句
else
条件为假所执行的语句
//多条语句
if(测试条件){
条件为真所执行的流程
}
else{
条件为假所执行的流程
}

1.分支结构运用

输入一个整数,如果该数值在2~10之间输出yes,否则输出no.

#include<stdio.h>
int main()
{
int a;
printf("请输入一个整数:");
scanf("%d", &a);
if (2 <= a && a <= 10)
printf("yes");
else
printf("no");
return 0;
}
【C语言_9】快速掌握分支结构!_if嵌套

2.if嵌套语句

1.嵌套例题

输入一个整数,如果该整数小于2,输出left,如果在2~10之间,输出in,如果大于10输出right.

#include<stdio.h>
int main()
{
int a;
printf("请输入一个整数:");
scanf("%d", &a);
if (a < 2) {
printf("left");
}
else {//else里面是一个完整的if语句结构,else后面的花括号可以省略
if (2 <= a && a <= 10) {
printf("in");
}
else {
printf("right");
}
}
return 0;
}
【C语言_9】快速掌握分支结构!_if嵌套_02

2.优化分支结构

#include<stdio.h>
int main()
{
int a;
printf("请输入一个整数:");
scanf("%d", &a);
if (a < 2) {
printf("left");
}
else if (2 <= a && a <= 10) {
printf("in");
}
else {
printf("right");
}
return 0;
}
【C语言_9】快速掌握分支结构!_分支结构_03

3.复杂嵌套例题

输入一个学生的分数x,x<60输出不及格,60<=x<70输出及格,70<=x<80,输出一般,80<=x<90,输出良好,90<=x<=100,输出优秀。

#include<stdio.h>
int main()
{
int x;
printf("请输入一名学生的成绩:");
scanf("%d", &x);
if (x< 60) {
printf("不及格");
}
else if (60 <= x && x < 70) {
printf("及格");
}
else if (70 <= x && x < 80) {
printf("一般");
}
else if (80 <= x && x < 90) {
printf("良好");
}
else {
printf("优秀");
}
return 0;
}
【C语言_9】快速掌握分支结构!_条件表达式_04

3.条件表达式

测试条件?条件1:条件2;
c=(a>b)?a:b;
表示如果a大于b,那么a赋值给c,否则把b赋值给c;
//等价于:
if(a>b)
c=a;
else
c=b;

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK