Files
C-plusplus-knowledge/第五章 循环和关系表达式.md
T
2025-01-03 17:03:59 +08:00

123 lines
2.5 KiB
Markdown

## 第五章 循环和关系表达式
### for循环
```cpp
for (initializations;test-expression;update-expression)
body;
//example
int example;
cin >> example;
for (int i = example;i;i--)
{
cout << i << endl;
}
```
- for循环的组成部分:
1. 设置初始值
2. 执行测试,看循环是否应当继续执行
3. 执行循环操作
4. 更新用于测试的值
- 循环只执行一次初始化,比较值与测试程序,为true执行循环体。
```cpp
int example;
cout << (example = 100) << endl;
cout << example << endl;
cout.setf(ios_base::boolalpha);
cout << (example > 3) << endl;
cout << (example < 3) << endl;
```
- cout.setf(ios_base::boolalpha)函数调用设置了一个标记,标记命令cout显示true和false 。
- x+15会计算新值,但没有副作用,而++x和x++就有副作用,改变了x值。
- 使用for循环访问字符串:
```cpp
//例子:写出一个函数,可以反向输出string的所有字符
#include <iostream>
#include <cstring>
void ShowString(std::string test);
int main()
{
std::string example = "hello world!";
ShowString(example);
return 0;
}
void ShowString(std::string test)
{
std::cout << test.size();
for (int i = test.size() - 1; i > 0; i--) {
std::cout << test[i];
}
}
```
#### 递增运算符(++)和(--)
```cpp
int a = 20;
int b = 20;
cout << a++ << endl; //20
cout << ++b << endl; //21
cout << a << b << endl; //21
```
- a++意味着使用a的当前值计算表达式,然后将a的值+1,而++b意思是先将b+1然后用新的值。
#### 副作用和顺序点
```cpp
int a = 20;
int b = 20;
// 21,22,23,24,25,26,27,28,29,30
while(a++ < 30)
{
cout << a << " ";
}
//21,22,23,24,25,26,27,28,29
while(++b < 30)
{
cout << b << " ";
}
```
- 前缀格式效率更高一些
- **对于for来说,i++和++i不会对for产生任何影响。**
#### 递增/递减运算符和指针
```cpp
double example[3] = {1.1,2.2,3.3};
double* pt = example;
cout << *pt << endl; //1.1
pt++;
cout << *pt << endl; //2.2
double* pt2 = example;
cout << *pt2++ << endl; //1.1
cout << *pt2 << endl; //2.2
cout << *++pt << endl; //3.3
```
- 后缀运算符的优先级更高,先运算后缀运算符后再进行解运算符(*)。
#### 组合赋值运算符
```cpp
i = i + by;
i += by;
//2
int k = 5;
k += 5;
int* pt = new int[5];
pt[1] = 12;
pt[1] += 5;
cout << pt[1] << endl; //17
*(pt+1) += 3;
cout << pt[1] << endl; //20
pt += 1;
cout << *pt << endl; //20
```