第四章 决策
如何比较数值
关系运算符
关系运算符 | 说明 |
> | 大于 |
< | 小于 |
== | 等于 |
>= | 大于等于 |
<= | 小于等于 |
!= | 不等于 |
返回bool类型
true
false
如果初始化是{}为空,数值变量初始化为0,bool初始化为false
std::boolalpha:可以把bool类型显示为true和false
std::noboolalpha:恢复默认
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s1{"abc"};
string s2{"ac"};
string s3{"ad"};
cout << boolalpha;
// 按字符串从左到右一次比较ASCII码大小
cout << (s1 < s2) << endl; // true
cout << (s1 > s3) << endl; // false
}
if语句
#include <iostream>
using namespace std;
int main()
{
cout << "Please input your age:";
int age{0};
cin >> age;
if (age <= 0) {
cout << "Please input correct age!" << endl;
}
else {
if (age < 18) {
cout << "You are a child!" << endl;
}
else if (age <= 60) {
cout << "You are a adult" << endl;
}
else {
cout << "You are a old man" << endl;
}
}
}
字符分类
#include <iostream>
using namespace std;
int main()
{
char c;
cin >> c;
cout << "大写字母:" << isupper(c) << endl; // 检测是否大写字母A~Z,true非0,false0
cout << "小写字母:" << islower(c) << endl; // 检测是否小写字母a~z。true非0,false0
cout << "大写或小写字母:" << isalpha(c) << endl; // 检测是否小写或大写字母A~Za~z。true非0,false0
cout << "数字:" << isdigit(c) << endl; // 检测是否数字0~9。true非0,false0
cout << "16进制:" << isxdigit(c) << endl; // 检测是否16进制数字0~9,a~f,A~F。true非0,false0
cout << "数字or字母:" << isalnum(c) << endl; // 检测是否字母or数字0~9A~Za~z。true非0,false0
cout << "空白:" << isspace(c) << endl; // 检测是否空白" "。true非0,false0
cout << "空格字符:" << isblank(c) << endl; // 检测是否空格" "、换行"\n"、回车"\r"、换页"\f"。true非0,false0
cout << "标点符:" << ispunct(c) << endl; // 检测是否标点符。true非0,false0
cout << "可以打印的(字母、数字、标点符、空格):" << isprint(c) << endl; // 检测是否字母、数字、标点符、空格。true非0,false0
cout << "控制符(不可以打印的):" << iscntrl(c) << endl; // 检测是否不可以打印的。true非0,false0
cout << "图形符(除空格外可以打印的):" << isalpha(c) << endl; // 检测是否图形符(除空格外可以打印的)。true非0,false0
}
字符转换
tolower()
toupper()
#include <iostream>
using namespace std;
int main()
{
char c;
char af;
cin >> c;
cout << "转换前:" << c << endl;
if (isalpha(c) == 0) {
cout << "不是大小写字母!" << endl;
return 0;
}
if (isupper(c) != 0) {
af = tolower(c);
}
if ((islower(c) != 0)) {
af = toupper(c);
}
cout << "转换后:" << af << endl;
return 0;
}
逻辑运算符
||:or
&&:and
!:非
条件运算符
#include <iostream>
using namespace std;
int main()
{
int a{ 0 };
int target{ 10 };
int b;
cin >> b;
a = b > target ? b : target;
cout << a << endl;
return 0;
}
switch
#include <iostream>
using namespace std;
int main()
{
int b;
cin >> b;
switch(b) {
case 0:
cout << "从0开始" << endl;
[[fullthrough]]; // 如果发生贯穿,有些编译器会警告,可以用fullthrough来告诉编译器不用告警
case 1:
cout << 1 << endl;
break; // 一般每个case后面都有break,否则会继续往后执行
case 2:
cout << 2 << endl;
break;
default:
cout << "不是1也不是2:" << b << endl;
break;
}
return 0;
}