01-基础语法/02-输出语句:修订间差异

来自三三百科
跳转到导航 跳转到搜索
33DAI留言 | 贡献
导入1个版本
33DAI留言 | 贡献
导入1个版本
 
(未显示另一用户的1个中间版本)
(没有差异)

2026年5月20日 (三) 18:12的最新版本

输出语句

使用 << 把要输出的内容依次传送到 cout

cout << "Hello World\n" << "Hello Hello\n";
cout << "World World";

cout 通常会被认为是"字符输出(character output)"或者"控制台输出(console output)"。

常见转义符

有一些特殊字符需要使用转义符的方式表示:

- '\n':换行符 - '\t':制表符 - '\:单引号 - '\"':双引号 - '\\':反斜杠字符本身

保留 [math]\displaystyle{ x }[/math] 位小数

- 头文件:#include <iostream>#include <iomanip>

 - 比赛环境中,你可以直接使用万能头文件 #include <bits/stdc++.h>,这包含了上面两个头文件。

- 保留 [math]\displaystyle{ x }[/math] 位小数输出语句:cout << fixed << setprecision(x) << a;

关于四舍五入

如果题目说保留 [math]\displaystyle{ x }[/math] 位小数,那么就按照上面方式输出就可以了。

但是需要注意的是,这种方式并不是我们直观中的四舍五入。

对于 [math]\displaystyle{ 4 }[/math] 舍和 [math]\displaystyle{ 6 }[/math] 入的部分是没有问题的,对于舍入位是 [math]\displaystyle{ 5 }[/math],且后面还有大于 [math]\displaystyle{ 0 }[/math] 的数位时也是没有问题的。但如果舍入位是 [math]\displaystyle{ 5 }[/math] 且后面没有其他数了,那么有可能会有两个小问题。

如果是 double 类型可以精确储存的数

那么会舍入到最接近的偶数数位,比如在保留 [math]\displaystyle{ 0 }[/math] 位小数的情况下:

- [math]\displaystyle{ 0.5 \to 0 }[/math] - [math]\displaystyle{ 1.5 \to 2 }[/math] - [math]\displaystyle{ 2.5 \to 2 }[/math] - [math]\displaystyle{ 3.5 \to 4 }[/math]

保留 [math]\displaystyle{ 2 }[/math] 位小数的情况下:

- [math]\displaystyle{ 1.125 \to 1.12 }[/math] - [math]\displaystyle{ 1.375 \to 1.38 }[/math]

如果是 double 类型无法精确储存的数

实际上储存的数可能会有一点点偏差,也会造成和我们所想不同。

比如如果输入 [math]\displaystyle{ 1.115 }[/math],那么保留 [math]\displaystyle{ 2 }[/math] 位小数输出的会是 [math]\displaystyle{ 1.11 }[/math],因为保留 [math]\displaystyle{ 20 }[/math] 位小数输出后,我们会发现实际储存的数大概是 [math]\displaystyle{ 1.11499999999999999112 }[/math],执行的自然是 [math]\displaystyle{ 4 }[/math] 舍操作。

现在的出题人一般都不会说四舍五入,而是用精度控制,比如相对或绝对误差在 [math]\displaystyle{ 10^{-6} }[/math](即 [math]\displaystyle{ 0.000001 }[/math])以内就算对,此时你保留 [math]\displaystyle{ 7 }[/math] 位小数就肯定够了。

刷新缓冲区

通常情况下,我们都更建议使用 '\n' 而不是 endl。因为 endl 会刷新缓冲区,导致多行输出的时候会比较慢。

而有的题目(比如交互题)就是需要每次输出之后刷新缓冲区,这个时候就可以使用 endl

或者如果你不放心,可以直接使用 cout.flush(); 来执行刷新缓冲区的操作。