前期知识:
变量,表达式与赋值:
陷阱:全整数除法:
//不同的 a = 5000*(b/20.0); a = 5000*(b/20);
#includeusing namespace std; int main() { int a,b(9); cout << 10*(b/11); cout << "n"; cout << 10*(b/11.0); return 0; }
类型转换:
新型转换(4种): static_cast<想要转换的形式>(想要转换的变量); static_cast(4); 去除变量的const属性; const_cast (); 旧型转换(2种): int(9.3); double(4); (int)9.3; (double)4;
自增与自减
陷阱:求值顺序
对于大部分运算符来说,子表达式的求值顺序是不固定的:
所以不建议在复杂的表达式中运用自增与自减符;
输入与输出:
- cin 输入
- cout 输出
- cerr 输出到控制台
使用以上语句时,要在程序开头写上:
#includeusing namespace std;
换行符:
“n”与endl;
单独需要换行时,推荐使用endl;
#include#include using namespace std; int main() { int a,b(9); string c; cin >> a; cin >> b; cin >> c; cout << a << endl << b << endl << c; return 0; }
规定double中小数点后的位置;
cout.self(ios::fixed); cout.self(ios::showpoint); cout.percision(2);
c++采用短路求值
掌握运算符的优先级:
| 符号 | 意义 |
|---|---|
| :: | 作用域运算符 |
| . | 点运算符 |
| -> | 成员选择符 |
| [] | 数组索引 |
| () | 函数调用 |
| ++ | 自增 |
| - - | 自减 |
| ! | 取反运算符 |
| - | 负号 |
| + | 正号 |
| * | 反引用 |
| & | 或址符 |
| new | 创建内存 |
| delete | 删除 |
| delete[] | 删除数组 |
| sizeof | 获得对象大小 |
| () | 类型转换 |
| * | 乘 |
| / | 取整 |
| % | 取余 |
| + | 加法 |
| - | 减法 |
| << | 插入运算符 |
| >> | 输出运算符 |
| < | 小于 |
| > | 大于 |
| <= | 小于会等于运算符 |
| >= | 大于或等于运算符 |
| == | 相等 |
| != | 不等 |
| && | 与 |
| || | 或 |
| = | 赋值 |
| += | 相加然后赋值 |
| -= | 相减然后赋值 |
| *= | 相乘然后赋值 |
| /= | 取整然后赋值 |
| %= | 取余然后赋值 |
| ?: | 条件运算符 |
| throw | 抛出异常 |
| , | 逗号 |
分支机构
if-else结构与C语言结构相似;
switch不光可以一对一,也可以多对一主要是取决与break;
#include#include using namespace std; int main() { int a; cout << "输入1-5之间的数n"; cin >> a; switch (a) { case 1: case 3: case 5:cout << "奇数";break; case 2: case 4:cout << "偶数";break; default:cout << "输入超出范围。"; } return 0; }
枚举:
enum day{
a,b,c,d,e}
条件运算符:
不推荐使用:
if (n1 > n2) max = n1; else max = n2; //运用三元运算符 max = (n1 > n2)? n1:n2;
循环结构:
1.while()
2.do-while()
3.for语句
4.continue
5.break
文件输入;
用到的是ifstream
#include#include #include using namespace std; int main() { string a; ifstream input_txt; input_txt.open("D:\C++_new\c++_1\test.txt"); input_txt >> a; cout << a; input_txt.close(); return 0; }
函数
带有返回值的预定义函数
#include#include using namespace std; int main() { int a; a = sqrt(9); cout << a; return 0; }
介绍一些预定义函数:
| 函数名 | 描述 | 实例 | 所属库 |
|---|---|---|---|
| sqrt | 平方根 | sqrt(4,0) | cmath |
| pow | 乘方 | pow(2.0,3.0) | cmath |
| abs | int类型绝对值 | abs(-7) | cstdlib |
| fabs | long型绝对值 | fabs(-700000) | cstdlib |
| ceil | 向上取值 | ceil(3.7) | cmath |
| floor | 向下取值 | floor(3.4) | cmath |
| exit | 退出程序 | exit(1) | cstdlib |
| rand | 随机数 | rand() | cstdlib |
| srand | 设置随机数因子 | srand(42) | cstdlib |
rand()生成的随机数不会无线大,一般为32767(两个字节整数的最大值)
自定义函数:这和之前C语言的定义函数是一样的;
需要注意的是,return其实可以用来结束函数
const关键字是用来定义常量的.
语句块与嵌套作用域
#include#include using namespace std; int main() { int a(89); { int a(11); cout << a << "n"; } cout << a << "n"; return 0; }



