C++支持的三种程序运行结构:
- 顺序结构: 程序按顺序执行,不发生跳转
- 选择结构: 依据条件是否满足,有选择的执行相应功能
- 循环结构: 依据条件是否满足,循环多次执行某段代码
选择结构
1. if语句
#include<iostream>
using namespace std;
int main()
{
//if
//用户输入分数,如果大于600,考生一本
//1、用户输入分数
int score = 0;
cout << "give a score:" << endl;
cin >> score;
//2、打印用户输入的分数
cout << "your score is:" << score << endl;
//3、判断分数是否大于600,如果是输出一本,
// 大于500考上二本,大于400考上三本,否则没有考上本科
//if条件后面没有分号,分号表示一个完整的语句
if (score > 600)
{
//cout << "yi ben" << endl;
if (score>700)
{
cout << "beijing university" << endl;
}
if (score > 680)
{
cout << "qinghua university" << endl;
}
}
else if(score>500)
{
cout << "er ben" << endl;
}
else if (score > 400)
{
cout << "san ben" << endl;
}
else
{
cout << "I am sorry" << endl;
}
system("pause");
return 0;
}
三个数找最大:
#include<iostream>
using namespace std;
int main()
{
//三只小猪称体重,判断哪只最重
//1、创建三只小猪的体重变化
int num1 = 0;
int num2 = 0;
int num3 = 0;
//2、让用户输入三只小猪的重量
cout << "pig A:" << endl;
cin >> num1;
cout << "pig B:" << endl;
cin >> num2;
cout << "pig C:" << endl;
cin >> num3;
cout << "pig A weight:" << num1 << endl;
cout << "pig B weight:" << num2 << endl;
cout << "pig C weight:" << num3 << endl;
//3、判断哪只最重
if (num1 > num2)
{
if (num1 > num3)
{
cout << "pig A is the biggest";
}
else
{
cout << "pig B is the biggest";
}
}
else
{
if (num2 > num3)
{
cout << "pig B is the biggest";
}
else
{
cout << "pig C is the biggest";
}
}
system("pause");
return 0;
}
2. 三目运算符
- 作用:通过三目运算符实现简单的判断
- 语法:表达式1?表达式2:表达式3(1为真执行1,否则2)
#include<iostream>
using namespace std;
int main()
{
//三目运算符
//创建三个变量a b c
//将a和b比较,将变量大的值赋给c
int a = 10;
int b = 20;
int c = 2;
c = (a > b ? a : b);
cout << "c=" << c << endl;
//C++中三目运算符返回的是变量,可以继续赋值
//将较小的变量赋值为100
(a < b ? a : b) = 100;
system("pause");
return 0;
}
3. switch语句
- 作用:执行多条件分支语句
案例:给电影打分10 – 9 经典,8 – 7 非常好,6 – 5 一般,5以下 烂片
#include<iostream>
using namespace std;
int main()
{
//1、给电影打分
cout<< "give the film a score:" << endl;
int score = 0;
cin >> score;
cout << "your score is:" <<score<< endl;
//2、根据分数提示结果
switch (score)
{
case 10:
cout << "jing dian" << endl;
break;//退出当前分支,不再往下执行
case 9:
cout << "jing dian" << endl;
break;
case 8:
cout << "fei chang hao" << endl;
break;
case 7:
cout << "fei chang hao" << endl;
break;
case 6:
cout << "yi ban" << endl;
break;
case 5:
cout << "yi ban" << endl;
break;
default:
cout << "lan pian" << endl;
break;
}
system("pause");
return 0;
}
- if 和switch区别?
switch判断时只能是整型或字符型,不能是区间
switch结构清晰、执行效率高