第四章
4.8
逻辑与和逻辑或运算符都是短路求值
4.10
while从标准输入读取整数,遇到42停止
while (cin >> num && num != 42)
4.12
C++中 < <= > >= 的优先级高于 == 和 !=
4.17(前置后置运算符)
- 养成使用前置版本的习惯
4.21
不要忘记auto如果需要引用的话需要手动添加
#include <iostream>
#include <vector>
#include <ctime>
#include <cstdlib>
using namespace std;
int main()
{
vector<int> vInt;
const int sz = 10; //数组维度
srand((unsigned)time(NULL));//生成随机数种子
//为数组赋值
for (int i = 0; i < sz; i++)
{
vInt.push_back(rand() % 100);//生成100以内的随机数
cout << vInt[i] << " ";
}
cout << endl;
for (auto &a : vInt)
{
a = a % 2 ? a * 2 : a;
}
cout << "调整后的数组是:";
for (int i = 0; i < sz; i++)
{
cout << vInt[i] << " ";
}
cout << endl;
return 0;
}
4.22
- if语句实现的版本
#include <iostream>
#include <string>
using namespace std;
int main()
{
string finalgrade;
int grade;
cout << "请输入您要检查的成绩:" << endl;
while (cin >> grade && grade >= 0 && grade <= 100)
{
if (grade > 90)
finalgrade = "high pass";
else if (grade > 75)
finalgrade = "pass";
else if (grade > 60)
finalgrade = "low pass";
else
finalgrade = "fail";
cout << "该成绩所处的档次是:" << finalgrade << endl;
cout << "请输入您要检查的成绩:" << endl;
}
return 0;
}
- 条件运算符实现
#include <iostream>
#include <string>
using namespace std;
int main()
{
string finalgrade;
int grade;
cout << "请输入您要检查的成绩:" << endl;
while (cin >> grade && grade >= 0 && grade <= 100)
{
finalgrade = (grade > 90) ? "high pass" :
((grade > 75) ? "pass" : ((grade > 60) ? "low pass" : "fail"));
cout << "该成绩所处的档次是:" << finalgrade << endl;
cout << "请输入您要检查的成绩:" << endl;
}
return 0;
}
4.25
4.27
按位与:& 逻辑与:&&
按位或: | 逻辑或: | |
4.28
C++只是规定了每种内置类型所占的最小空间,实际上占据多少空间依赖于具体的实现
对数组使用sizeof运算符,得到整个数组所占空间的大小。
4.34
算术转换:4.11节
- 运算符的运算对象将会转换成最宽的类型
- 表达式中既有浮点类型也有整数类型时,整数值将转换成相应的浮点类型
附运算符优先级表: