> For the complete documentation index, see [llms.txt](https://overleaf-pro.ayaka.space/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://overleaf-pro.ayaka.space/latex/zh-cn/ge-shi-hua/10-counters.md).

# 计数器

## LaTeX 计数器简介

基于 LaTeX 的排版是一种特殊形式的编程：你使用一种排版语言（LaTeX 命令）提供“指令”，其结果是一个输出：编译后的 LaTeX 文档，以 PDF 文件形式呈现。与任何编程工作一样，你很可能需要让 LaTeX 临时存储整数值，以便在文档（代码）中稍后重复使用——你可能想要：

* 在你的文档中排版这些已存储的整数
* 为文档中的某些元素提供自动编号
* 将它们用作变量来控制条件代码（或循环）
* 通过用某个固定值增加/减少来更改和更新它们的值
* 将它们重置为完全不同的值

这类整数处理活动在“常规”编程语言中极为常见，例如 Javascript、C、Lua 或你选择的任何其他语言；在这些语言中，你通常会声明（为其创建一个名称）一个变量（用来保存整数），然后为其赋值。LaTeX 排版语言也提供了类似的能力，尽管其实现方式相当不同，我们将在下面探讨。

本质上，LaTeX 计数器就是一个“LaTeX 变量”的名称，用于存储整数值，可用于上面列出的操作，以及更多用途。LaTeX 本身使用了许多内部计数器，用于对页面、章节、表格、图片、项目符号/编号列表等进行编号。本文将说明如何访问和修改这些计数器，以及如何创建和使用新的计数器。

## 用于处理计数器的 LaTeX 命令

下面列出的是 LaTeX 的计数器命令，并在后续章节中链接到其说明。

创建和递增计数器：

* [`\newcounter{somecounter}[anothercounter]`](#newcountersomecounteranothercounter)
* [`\setcounter{somecounter}{number}`](#setcountersomecounternumber)
* [`\addtocounter{somecounter}{number}`](#addtocountersomecounternumber)
* [`\stepcounter{somecounter}`](#stepcountersomecounter)
* [`\refstepcounter{somecounter}`](#refstepcountersomecounter)

访问并打印计数器值：

* [`\arabic{somecounter}`](#arabicsomecounter)
* [`\roman{somecounter}`](#romansomecounter)
* [`\Roman{somecounter}`](#romanoutput)
* [`\alph{somecounter}`](#alphsomecounter)
* [`\Alph{somecounter}`](#alphoutput)
* [`\fnsymbol{somecounter}`](#fnsymbolsomecounter)
* [`\value{somecounter}`](#valuesomecounter)

其他计数器命令：

* [`\counterwithin{somecounter}{anothercounter}`](#counterwithinsomecounteranothercounter)
* [`\counterwithout{somecounter}{anothercounter}`](#counterwithoutsomecounteranothercounter)

### 创建和递增计数器

#### \newcounter{somecounter}\[anothercounter]

用于定义一个新计数器。第二个参数，括在 `[]`中，是可选的，但在使用时它定义 `*somecounter*` 为一个新计数器，它会在 `*anothercounter*` 被步进时重置。 `\newcounter` 常以更简单的形式使用 `\newcounter{*somecounter*}` 这会创建 `*somecounter*` 并将其初始化为 0。

* **注意**：对于由 `\newcounter` 命令创建的每个计数器，它 *也* 会定义一个可用于排版该计数器值的命令。例如， `\newcounter{*mycounter*}` 定义一个名为 `\the*mycounter*`的命令。下面的 LaTeX 代码片段给出了一个示例，你可以通过提供的链接在 Overleaf 中将其作为完整文档打开：

```latex
\newcounter{mycounter}
\setcounter{mycounter}{42}
现在你可以写 \verb|\themycounter| 来得到 \themycounter。
```

[在 Overleaf 中打开此 LaTeX 片段](https://www.overleaf.com/docs?engine=pdflatex\&snip_name=Using+newcounter\&snip=%5Cdocumentclass%7Barticle%7D%0A%5Cbegin%7Bdocument%7D%0A%5Cnewcounter%7Bmycounter%7D%0A%5Csetcounter%7Bmycounter%7D%7B42%7D%0AYou+can+now+write+%5Cverb%7C%5Cthemycounter%7C+to+obtain+%5Cthemycounter.%0A%5Cend%7Bdocument%7D)

此示例生成 $$\text{You can now write }\verb|\themycounter|\text{ to obtain 42.}$$

* **注意**：如果 `*mycounter*` 已经被定义，LaTeX 将报错 `c@mycounter already defined`，如下例所示，你可以在 Overleaf 中打开。

```latex
\newcounter{mycounter}
...很多代码... 但我们忘了又写了一次 \verb|\newcounter{mycounter}|
\newcounter{mycounter}
```

[在 Overleaf 中打开此 ***会产生错误的代码*** 在 Overleaf 中](https://www.overleaf.com/docs?engine=pdflatex\&snip_name=Using+newcounter\&snip=%5Cdocumentclass%7Barticle%7D%0A%5Cbegin%7Bdocument%7D%0A%5Cnewcounter%7Bmycounter%7D%0A...lots+of+code...+but+we+forget+and+write+%5Cverb%7C%5Cnewcounter%7Bmycounter%7D%7C+again%0A%5Cnewcounter%7Bmycounter%7D%0A%5Cend%7Bdocument%7D)

#### \setcounter{somecounter}{number}

设置 `*somecounter*` 为包含值 `*number*`.

* **注意**: `*number*` 可以是正数或负数。

下面的 LaTeX 代码片段给出了一个示例，你可以通过提供的链接在 Overleaf 中将其作为完整文档打开：

```latex
\noindent 创建一个新计数器 \texttt{myvar}，并将其赋值为 \texttt{42}。
\vspace{10pt}

\newcounter{myvar}
\setcounter{myvar}{42}

\noindent 写入 \verb|\themymar| 会排版出 \texttt{\themyvar}。
\vspace{10pt}

\noindent 接下来，我们将把 \texttt{myvar} 改为 \texttt{-42}，写入 \verb|\setcounter{myvar}{-42}|
\setcounter{myvar}{-42}。现在，写入 \verb|\themyvar| 会输出 \texttt{\themyvar}。
```

[在 Overleaf 中打开此 LaTeX 片段](https://www.overleaf.com/docs?engine=pdflatex\&snip_name=Using+newcounter\&snip=%5Cdocumentclass%7Barticle%7D%0A%5Cbegin%7Bdocument%7D%0A%5Cnoindent+Create+a+new+counter+%5Ctexttt%7Bmyvar%7D+and+assign+it+the+value+%5Ctexttt%7B42%7D.%0A%5Cvspace%7B10pt%7D%0A%0A%5Cnewcounter%7Bmyvar%7D%0A%5Csetcounter%7Bmyvar%7D%7B42%7D+%0A%0A%5Cnoindent+Writing+%5Cverb%7C%5Cthemymar%7C+typesets+%5Ctexttt%7B%5Cthemyvar%7D.%0A%5Cvspace%7B10pt%7D%0A%0A%5Cnoindent+Next%2C+we%27ll+change+%5Ctexttt%7Bmyvar%7D+to+%5Ctexttt%7B-42%7D%2C+writing+%5Cverb%7C%5Csetcounter%7Bmyvar%7D%7B-42%7D%7C%0A%5Csetcounter%7Bmyvar%7D%7B-42%7D.+Now%2C+writing+%5Cverb%7C%5Cthemyvar%7C+outputs+%5Ctexttt%7B%5Cthemyvar%7D.%0A%5Cend%7Bdocument%7D)

#### \addtocounter{somecounter}{number}

使计数器增加 `*somecounter*` 增加量为 `*number*`.

* **注意**: `*number*` 可以为正数，用于增加计数器值，也可以为负数，用于减少它。例如：

```latex
\addtocounter{somecounter}{-1} % 将 somecounter 减少 1
```

下面的 LaTeX 代码片段给出了一个示例，你可以通过提供的链接在 Overleaf 中将其作为完整文档打开：

```latex
\noindent 创建一个新计数器 \texttt{myvar}，并将其赋值为 \texttt{42}。
\vspace{10pt}

\newcounter{myvar}
\setcounter{myvar}{42}

\noindent 写入 \verb|\themymar| 会排版出 \texttt{\themyvar}。
\vspace{10pt}

\noindent 接下来，我们将通过写入 \verb|\addtocounter{myvar}{100}| 将 \texttt{myvar} 改为 \texttt{142}。现在，写入 \verb|\themyvar| 会输出 \texttt{\themyvar}。
```

[在 Overleaf 中打开此 LaTeX 片段](https://www.overleaf.com/docs?engine=pdflatex\&snip_name=Using+addtocounter\&snip=%5Cdocumentclass%7Barticle%7D%0A%5Cbegin%7Bdocument%7D%0A%5Cnoindent+Create+a+new+counter+%5Ctexttt%7Bmyvar%7D+and+assign+it+the+value+%5Ctexttt%7B42%7D.%0A%5Cvspace%7B10pt%7D%0A%0A%5Cnewcounter%7Bmyvar%7D%0A%5Csetcounter%7Bmyvar%7D%7B42%7D+%0A%0A%5Cnoindent+Writing+%5Cverb%7C%5Cthemymar%7C+typesets+%5Ctexttt%7B%5Cthemyvar%7D.%0A%5Cvspace%7B10pt%7D%0A%0A%5Cnoindent+Next%2C+we%E2%80%99ll+change+%5Ctexttt%7Bmyvar%7D+to+%5Ctexttt%7B142%7D+by+writing+%5Cverb%7C%5Caddtocounter%7Bmyvar%7D%7B100%7D%7C%5Caddtocounter%7Bmyvar%7D%7B100%7D.+Now%2C+writing+%5Cverb%7C%5Cthemyvar%7C+outputs+%5Ctexttt%7B%5Cthemyvar%7D.%0A%5Cend%7Bdocument%7D)

#### \stepcounter{somecounter}

递增 `*somecounter*` 1。下面的 LaTeX 代码片段给出了一个示例，你可以通过提供的链接在 Overleaf 中将其作为完整文档打开：

```latex
如果我们通过写入 \verb|\newcounter{mycounter}| 创建一个新计数器
\newcounter{mycounter} 那么计数器 \texttt{mycounter} 就会被创建，并且
初始化为零，正如你写入 \verb|\themycounter| 时所见：
\texttt{mycounter} 当前存储的是：\themycounter。

如果我们现在写入 \verb|\stepcounter{mycounter}|\stepcounter{mycounter}，那么
\verb|\themycounter| 现在包含值 \themycounter。
```

[在 Overleaf 中打开此 LaTeX 片段](https://www.overleaf.com/docs?engine=pdflatex\&snip_name=Using+stepcounter\&snip=%5Cdocumentclass%7Barticle%7D%0A%5Cbegin%7Bdocument%7D%0AIf+we+create+a+new+counter+by+writing+%5Cverb%7C%5Cnewcounter%7Bmycounter%7D%7C%0A%5Cnewcounter%7Bmycounter%7D+then+the+counter+%5Ctexttt%7Bmycounter%7D+is+created+and+%0Ainitialized+to+zero%2C+as+you+can+see+if+you+write+%5Cverb%7C%5Cthemycounter%7C%3A%0A%5Ctexttt%7Bmycounter%7D+currently+stores%3A+%5Cthemycounter.+%0A%0AIf+we+now+write+%5Cverb%7C%5Cstepcounter%7Bmycounter%7D%7C%5Cstepcounter%7Bmycounter%7D+then+%0A%5Cverb%7C%5Cthemycounter%7C+now+contains+the+value+%5Cthemycounter.%0A%5Cend%7Bdocument%7D)

#### \refstepcounter{somecounter}

增加 `*somecounter*` 1，并使其对引用机制可见，同时设置该值，使你可以使用 `\label` 随后。

**使用 \refstepcounter 的示例**

下面的示例使用 `\refstepcounter` 为一个……创建一个新计数器 `示例` 环境，并使用 `\label` 和 `\ref` 来演示使用 `示例` 计数器变量进行引用。

```latex
\documentclass{article}

\newcounter{example}[section]
\newenvironment{example}[1][]{\refstepcounter{example}\par\medskip
   \noindent\textbf{Example~\theexample. #1} \rmfamily}{\medskip}

\begin{document}
三个示例
\begin{example}
在第一个示例中创建标签 \verb|\label{ex:1}|\label{ex:1}。这是第一个示例。\texttt{example} 计数器将在每个新的 \verb|\section| 开始时重置。
\end{example}

\begin{example}
这里还有另一个带编号的示例。创建第二个 \verb|\label{ex:2}|\label{ex:2}，以便稍后引用这个示例。在示例 \ref{ex:1} 中，我们读到……某些内容。
\end{example}

\begin{example}
这里还有另一个带编号的示例：使用 \verb|\theexample| 来排版当前分配给 \texttt{example} 计数器的编号：它是 \theexample。
\end{example}

\section{Another section}
我们刚刚开始了一个新节，这意味着 \texttt{example} 计数器已被设为 \theexample。
我们将引用上一节中的示例（示例 \ref{ex:1} 和 \ref{ex:2}）。这是一个毫无用途的虚拟节，只是用来包含文字。该节的 \texttt{section} 计数器可以使用 \verb|\thesection| 排版：它当前被赋予的值是 \thesection。

\begin{example}
这是本节中的第一个示例：\texttt{example} 计数器已经递增，现在设为 \theexample。
\end{example}
\end{document}
```

[在 Overleaf 中打开此 `\refstepcounter` Overleaf 中的示例](https://www.overleaf.com/docs?engine=pdflatex\&snip_name=An+example+using+refstepcounter\&snip=%5Cdocumentclass%7Barticle%7D%0A%0A%5Cnewcounter%7Bexample%7D%5Bsection%5D%0A%5Cnewenvironment%7Bexample%7D%5B1%5D%5B%5D%7B%5Crefstepcounter%7Bexample%7D%5Cpar%5Cmedskip%0A+++%5Cnoindent%5Ctextbf%7BExample%7E%5Ctheexample.+%231%7D+%5Crmfamily%7D%7B%5Cmedskip%7D%0A%0A%5Cbegin%7Bdocument%7D%0A%5Csection%7BThree+examples%7D%0A%5Cbegin%7Bexample%7D%0ACreate+a+label+in+this+first+example+%5Cverb%7C%5Clabel%7Bex%3A1%7D%7C%5Clabel%7Bex%3A1%7D.+This+is+the+first+example.+The+%5Ctexttt%7Bexample%7D+counter+will+be+reset+at+the+start+of+each+new+each+document+%5Cverb%7C%5Csection%7C.%0A%5Cend%7Bexample%7D%0A%0A%5Cbegin%7Bexample%7D%0AAnd+here%27s+another+numbered+example.+Create+a+second+%5Cverb%7C%5Clabel%7Bex%3A2%7D%7C%5Clabel%7Bex%3A2%7D+to+later+reference+this+one.+In+Example+%5Cref%7Bex%3A1%7D+we+read...+something.+%0A%5Cend%7Bexample%7D%0A%0A%5Cbegin%7Bexample%7D%0AAnd+here%27s+another+numbered+example%3A+use+%5Cverb%7C%5Ctheexample%7C+to+typeset+the+number+currently+assigned+to+the+%5Ctexttt%7Bexample%7D+counter%3A+it+is++%5Ctheexample.%0A%5Cend%7Bexample%7D%0A%0A%5Csection%7BAnother+section%7D%0AWe%27ve+just+started+a+new+section+meaning+that+the++%5Ctexttt%7Bexample%7D+counter+has+been+set+to+%5Ctheexample.++%0AWe%27ll+reference+examples+from+the+previous+section+%28Examples+%5Cref%7Bex%3A1%7D+and+%5Cref%7Bex%3A2%7D%29.++This+is+a+dummy+section+with+no+purpose+whatsoever+but+to+contain+text.+The+%5Ctexttt%7Bsection%7D+counter+for+this+section+can+be+typeset+using+%5Cverb%7C%5Cthesection%7C%3A+it+is++currently+assigned+the+value+of+%5Cthesection.%0A%0A%5Cbegin%7Bexample%7D%0AThis+is+the+first+example+in+this+section%3A+the+%5Ctexttt%7Bexample%7D+counter+has+been+stepped+and+now+set+to+%5Ctheexample.+%0A%5Cend%7Bexample%7D%0A%5Cend%7Bdocument%7D)

**代码摘要**

在这个示例中，新环境 `示例` 被定义；这个环境有 3 个与计数相关的命令：

* `\newcounter{example}[section]`：创建一个名为 `示例` 的计数器，每当 `section` 计数器增加时，它都会被重置为 0。你可以放入任意其他计数器来代替 `section` ；如果你不希望计数器自动重置，也可以省略该参数。
* `\refstepcounter{example}`：使 `示例` 计数器加 1，并使其对引用机制可见，这样你就可以使用 `\label` 随后。
* `\theexample`：打印计数器的当前值 `示例`.

有关用户自定义环境的更多信息，请参见 [关于定义新环境的文章](/latex/zh-cn/ming-ling/02-environments.md#defining-a-new-environment)

### 访问并打印计数器值

以下讨论基于 LaTeX 默认设置，即尚未应用用户加载的宏包所做的任何自定义之前。

#### \arabic{somecounter}

输出……的表示形式 `*somecounter*` 为阿拉伯数字：1、2、3……

#### \roman{somecounter}

输出……的表示形式 `*somecounter*` 为小写罗马数字：i、ii、iii……

* **注意**：如果 `*somecounter*` $$\leq$$ `0` 不会产生输出。此外，将 *极其* 较大的整数值转换为小写罗马数字可能需要很长时间才能完成——并且会产生一长串 `m` 字符（表示数字 `1000`).
* **提示**：如果你对 TeX 将阿拉伯数字转换为罗马数字所使用的算法感兴趣，可以阅读这篇关于 [罗马数字算法](https://www.hanshq.net/roman-numerals.html#tex).

#### \Roman{somecounter}

输出……的表示形式 `*somecounter*` 为大写罗马数字：I、II、III……

* **注意**：如果 `*somecounter*` $$\leq$$ `0` 不会产生输出。此外，将 *极其* 较大的整数值转换为大写罗马数字可能需要很长时间才能完成——并且会产生一长串 `M` 字符（表示数字 `1000`).
* **提示**：如果你对 TeX 将阿拉伯数字转换为罗马数字所使用的算法感兴趣，可以阅读这篇关于 [罗马数字算法](https://www.hanshq.net/roman-numerals.html#tex).

#### \alph{somecounter}

输出……的表示形式 `*somecounter*` 为小写字母，其中 a=1，b=2，c=3……

* **注意**: `*somecounter*` 必须在范围 `1` $$\leq$$ `*somecounter*` $$\leq$$ `26`内，否则将触发错误 `！LaTeX 错误：计数器过大。`

#### \Alph{somecounter}

输出……的表示形式 `*somecounter*` 为大写字母，其中 A=1，B=2，C=3……

* **注意**: `*somecounter*` 必须在范围 `1` $$\leq$$ `*somecounter*` $$\leq$$ `26`内，否则将触发错误 `！LaTeX 错误：计数器过大。`

#### \fnsymbol{somecounter}

输出……的表示形式 `*somecounter*` 为脚注符号，其中 1 =∗，2 =†……

* **注意**: `*somecounter*` 必须在范围 `1` $$\leq$$ `*somecounter*` $$\leq$$ `9`内，否则将触发错误 `！LaTeX 错误：计数器过大。`

|                      |                       |
| -------------------- | --------------------- |
| ……的值 `*somecounter*` | 由……排版出的字符 `\fnsymbol` |
| 1                    | \*                    |
| 2                    | †                     |
| 3                    | ‡                     |
| 4                    | §                     |
| 5                    | ¶                     |
| 6                    | ∥                     |
| 7                    | ∗∗                    |
| 8                    | ††                    |
| 9                    | ‡‡                    |

#### 打印计数器值的示例

以下示例演示了以下命令的用法 `\arabic{*somecounter*}`, `\roman{*somecounter*}`, `\Roman{*somecounter*}`, `\alph{*somecounter*}`, `\Alph{*somecounter*}`以及 `\fnsymbol{*somecounter*}`.

```latex
\newcounter{somecounter}
\setcounter{somecounter}{9}
\begin{itemize}
    \item \verb|\arabic{somecounter}| 会将 \texttt{somecounter} 的值 \thesomecounter{} 排版为 \arabic{somecounter}
    \item \verb|\roman{somecounter}| 会将 \texttt{somecounter} 的值 \thesomecounter{} 排版为 \roman{somecounter}
    \item \verb|\Roman{somecounter}| 会将 \texttt{somecounter} 的值 \thesomecounter{} 排版为 \Roman{somecounter}
    \item \verb|\alph{somecounter}| 会将 \texttt{somecounter} 的值 \thesomecounter{} 排版为 \alph{somecounter}
   \item \verb|\Alph{somecounter}| 会将 \texttt{somecounter} 的值 \thesomecounter{} 排版为 \Alph{somecounter}
    \item \verb|\fnsymbol{somecounter}| 会将 \texttt{somecounter} 的值 \thesomecounter{} 排版为 \fnsymbol{somecounter}
\end{itemize}
```

[在 Overleaf 中打开此 LaTeX 片段](https://www.overleaf.com/docs?engine=pdflatex\&snip_name=Converting+counter+values\&snip=%5Cdocumentclass%7Barticle%7D%0A%5Cbegin%7Bdocument%7D%0A%5Cnewcounter%7Bsomecounter%7D%0A%5Csetcounter%7Bsomecounter%7D%7B9%7D%0A%5Cbegin%7Bitemize%7D%0A++++%5Citem+%5Cverb%7C%5Carabic%7Bsomecounter%7D%7C+typesets+the+%5Ctexttt%7Bsomecounter%7D+value+of++%5Cthesomecounter%7B%7D+as+%5Carabic%7Bsomecounter%7D+%0A++++%5Citem+%5Cverb%7C%5Croman%7Bsomecounter%7D%7C+typesets+the+%5Ctexttt%7Bsomecounter%7D+value+of++%5Cthesomecounter%7B%7D+as++%5Croman%7Bsomecounter%7D%0A++++%5Citem+%5Cverb%7C%5CRoman%7Bsomecounter%7D%7C+typesets+the+%5Ctexttt%7Bsomecounter%7D+value+of++%5Cthesomecounter%7B%7D+as++%5CRoman%7Bsomecounter%7D%0A++++%5Citem+%5Cverb%7C%5Calph%7Bsomecounter%7D%7C+typesets+the+%5Ctexttt%7Bsomecounter%7D+value+of++%5Cthesomecounter%7B%7D+as++%5Calph%7Bsomecounter%7D%0A+++%5Citem+%5Cverb%7C%5CAlph%7Bsomecounter%7D%7C+typesets+the+%5Ctexttt%7Bsomecounter%7D+value+of++%5Cthesomecounter%7B%7D+as++%5CAlph%7Bsomecounter%7D%0A++++%5Citem+%5Cverb%7C%5Cfnsymbol%7Bsomecounter%7D%7C+typesets+the+%5Ctexttt%7Bsomecounter%7D+value+of++%5Cthesomecounter%7B%7D+as++%5Cfnsymbol%7Bsomecounter%7D%0A%5Cend%7Bitemize%7D%0A%5Cend%7Bdocument%7D)

此示例生成以下输出：

![LaTeX 中计数器转换示例](/files/09919497fc10cde07ec9c404713cdc88a319befe)

#### \value{somecounter}

根据 LaTeX 源代码中的描述，该命令的用途是“以 TeX 数字形式访问计数器的值”：也就是说，你会使用 `\value{somecounter}` 在 LaTeX 期望处理数值的场景中。

**关于 \value 命令的（可选）背景说明**

人们很容易认为命令 `\value{*somecounter*}` 会 *直接* 排版……的值 `*somecounter*`，但事实并非如此。它旨在在其他命令中使用，以 TeX 数字形式访问计数器的值，而不是命令 `\thesomecounter` 它会生成……的打印表示形式 `*somecounter*`.

在 LaTeX 源代码中， `\value` 被定义为：

```latex
\def\value#1{\csname c@#1\endcsname}
```

因此， `\value{*somecounter*}` 会创建 LaTeX 内部控制序列 `\c@somecounter` 的一个实例，其中包含该计数器的值 `*somecounter*`.

**示例**

以下示例展示了 \value 的一个基本用例 `\value`.

```latex
首先声明两个新计数器：
\begin{verbatim}
\newcounter{first}
\newcounter{second}
\end{verbatim}

\newcounter{first}
\newcounter{second}

稍后在你的代码中设置它们的值：
\begin{verbatim}
\setcounter{first}{100}
\setcounter{second}{50}
\end{verbatim}

\setcounter{first}{100}
\setcounter{second}{50}
然后你继续编写更多 \LaTeX{} 代码...\vspace{10pt}

有时我们可能希望将计数器 \texttt{second} 的值加到计数器 \texttt{first} 上。一种方法是使用 \verb|\value| 来获取 \texttt{second} 计数器中存储的 \textit{当前} 值：

\begin{verbatim}
\addtocounter{first}{\value{second}}
\end{verbatim}

\addtocounter{first}{\value{second}}\noindent \texttt{first} 的值可以通过 \verb|\thefirst| 输出：\thefirst。我们也可以写 \verb|\the\value{first}|，它同样会排版 \the\value{first}。不过，写 \verb|\value{first}| 会产生错误 \texttt{Missing number, treated as zero}，因为 \LaTeX{} 随后会尝试执行内部命令 \verb|\c@first|。取消下面这一行的注释即可生成该错误：
\begin{verbatim}
%\value{first}
\end{verbatim}
%\value{first}
```

[在 Overleaf 中打开此代码片段](https://www.overleaf.com/docs?engine=pdflatex\&snip_name=Using+the+value+command\&snip=%5Cdocumentclass%7Barticle%7D%0A%5Cbegin%7Bdocument%7D%0A%5Cnoindent+Start+by+declaring+two+new+counters%3A%0A%5Cbegin%7Bverbatim%7D%0A%5Cnewcounter%7Bfirst%7D%0A%5Cnewcounter%7Bsecond%7D++++%0A%5Cend%7Bverbatim%7D%0A%0A%5Cnewcounter%7Bfirst%7D%0A%5Cnewcounter%7Bsecond%7D%0A%0A%5Cnoindent+Sometime+later+in+your+code+you+set+their+values%3A%0A%5Cbegin%7Bverbatim%7D%0A%5Csetcounter%7Bfirst%7D%7B100%7D%0A%5Csetcounter%7Bsecond%7D%7B50%7D++++%0A%5Cend%7Bverbatim%7D%0A%0A%5Csetcounter%7Bfirst%7D%7B100%7D%0A%5Csetcounter%7Bsecond%7D%7B50%7D++%0A%5Cnoindent+Then+you+write+more+%5CLaTeX%7B%7D+code...%5Cvspace%7B10pt%7D%0A%0A%5Cnoindent+At+some+point+we+might+want+to+add+the+value+of+counter+%5Ctexttt%7Bsecond%7D+to+counter+%5Ctexttt%7Bfirst%7D.+One+way+to+do+that+is+using+%5Cverb%7C%5Cvalue%7C+to+obtain+the+%5Ctextit%7Bcurrent%7D+value+stored+in+the+%5Ctexttt%7Bsecond%7D+counter%3A%0A%0A%5Cbegin%7Bverbatim%7D%0A%5Caddtocounter%7Bfirst%7D%7B%5Cvalue%7Bsecond%7D%7D%0A%5Cend%7Bverbatim%7D%0A%0A%5Caddtocounter%7Bfirst%7D%7B%5Cvalue%7Bsecond%7D%7D%5Cnoindent+The+value+of+%5Ctexttt%7Bfirst%7D+can+be+output+by+%5Cverb%7C%5Cthefirst%7C%3A+%5Cthefirst.+We+can+also+write+%5Cverb%7C%5Cthe%5Cvalue%7Bfirst%7D%7C+which+also+typesets+%5Cthe%5Cvalue%7Bfirst%7D.+However%2C++writing+%5Cverb%7C%5Cvalue%7Bfirst%7D%7C+will+generate+the+error+%5Ctexttt%7BMissing+number%2C+treated+as+zero%7D+because+%5CLaTeX%7B%7D+then+tries+to+execute+the+internal+command+%5Cverb%7C%5Cc%40first%7C.+Uncomment+the+following+line+to+generate+the+error%3A%0A%5Cbegin%7Bverbatim%7D%0A%25%5Cvalue%7Bfirst%7D%0A%5Cend%7Bverbatim%7D%0A%25%5Cvalue%7Bfirst%7D%0A%5Cend%7Bdocument%7D)

此示例生成以下输出：

![使用 \value 命令的示例](/files/8da4941bdc3775b597ee877637223ff491e78d6a)

### 其他计数器命令

这里介绍这些命令 `\counterwithin` 和 `\counterwithout` 它们起源于 [`chngcntr` 宏包](https://ctan.org/pkg/chngcntr) ，但现在已被集成到 LaTeX 本身中——参见 [LaTeX 新闻，2018 年 4 月](https://www.latex-project.org/news/latex2e-news/ltnews28.pdf)。 `chngcntr` [包文档](https://mirror.ox.ac.uk/sites/ctan.org/macros/latex/contrib/chngcntr/chngcntr.pdf) 给出了以下说明，有助于理解这些命令的用途：

开启 `\counterwithin`:

> 有时希望将由以下方式定义的计数器 `\newcounter{<ctr>}` 改为表现得仿佛它是这样定义的： `\newcounter{<ctr>}[<within>]`。该宏包提供了命令 `\counterwithin{<ctr>}{<within>}` 来实现这一点。

开启 `\counterwithout`:

> 同样，命令 `\counterwithout{<ctr>}{<within>}` 可将通过 `\newcounter{<ctr>}[<within>]` 创建的计数器改为表现得仿佛它是由 `\newcounter{<ctr>}`.

本质上，这两个命令提供了一种将两个计数器关联（`\counterwithin`）或取消关联（`\counterwithout`）的方法，在它们被定义之后。

**\counterwithin{somecounter}{anothercounter}**

重置 `*somecounter*` 为 0，每当 `*anothercounter*` 被步进时都会执行，这是一种连接这两个计数器的机制。除了创建连接之外，该命令还重新定义了由 `\the*somecounter*`：它不再输出计数器 `*somecounter*` 的值，而是生成 `<anothercounter 的值>**.**<somecounter 的值>`。带星号的形式（`\counterwithin*{somecounter}{anothercounter}`）不会重新定义 `*somecounter*`，如下例所示——请选择代码下方的链接在 Overleaf 中打开：

```latex
\documentclass{article}
\begin{document}
\section{A short example}
\newcounter{example}
\counterwithin{example}{section}
\newcounter{exampletwo}
\counterwithin*{exampletwo}{section}
\setcounter{example}{100}
\setcounter{exampletwo}{100}
\begin{itemize}
\item \verb|\theexample| 会排版出 \theexample
\item \verb|\theexampletwo| 会排版出 \theexampletwo
\end{itemize}
\end{document}
```

[在 Overleaf 中打开此 `\counterwithin` Overleaf 中的示例](https://www.overleaf.com/docs?engine=\&snip_name=Example+of+starred+version+of+counterwithin\&snip=%5Cdocumentclass%7Barticle%7D%0A%5Cbegin%7Bdocument%7D%0A%5Csection%7BA+short+example%7D%0A%5Cnewcounter%7Bexample%7D%0A%5Ccounterwithin%7Bexample%7D%7Bsection%7D%0A%5Cnewcounter%7Bexampletwo%7D%0A%5Ccounterwithin%2A%7Bexampletwo%7D%7Bsection%7D%0A%5Csetcounter%7Bexample%7D%7B100%7D%0A%5Csetcounter%7Bexampletwo%7D%7B100%7D%0A%5Cbegin%7Bitemize%7D%0A%5Citem+%5Cverb%7C%5Ctheexample%7C+typesets+%5Ctheexample%0A%5Citem+%5Cverb%7C%5Ctheexampletwo%7C+typesets+%5Ctheexampletwo%0A%5Cend%7Bitemize%7D%0A%5Cend%7Bdocument%7D)

此示例生成以下输出：

![使用 \counterwithin 命令](/files/3cc349e75c7fe3ec4754c15b1af401fd8272e05c)

你可以将 `\counterwithin` 用于 LaTeX 提供的标准计数器，例如：

* `section`：由 `\section` 命令
* `equation` 由……使用 `equation` 环境

或者用于你创建的计数器。

**\counterwithin 和 \counterwithin\* 的示例**

下面的代码提供了一个更完整的使用 `\counterwithin` 和 `\counterwithin*`的示例；请选择代码下方的链接在 Overleaf 中打开：

```latex
\documentclass{article}
\counterwithin{equation}{section}
\newcounter{example}
\counterwithin*{example}{section}
\newenvironment{example}[1][]{%
\stepcounter{example}%
\par\vspace{5pt}\noindent
\fbox{\textbf{Example~\thesection.\theexample}}%
\hrulefill\par\vspace{10pt}\noindent\rmfamily}%
{\par\noindent\hrulefill\vrule width10pt height2pt depth2pt\par}
\begin{document}
\section{First equation}
一些引言文本...
\begin{example}
\begin{equation}
    f(x)=\frac{x}{1+x^2}
\end{equation}
\end{example}

\subsection{更多细节}
\begin{example}
这里我们讨论
\begin{equation}
    f(x)=\frac{x+1}{x-1}
\end{equation}
... 但什么也不说
\end{example}

\subsubsection{更进一步的细节}
\begin{example}
\begin{equation}
    f(x)=\frac{x^2}{1+x^3}
\end{equation}
\begin{equation}
    f(x+\delta x)=\frac{(x+\delta x)^2}{1+(x+\delta x)^3}
\end{equation}
\end{example}

\section{Third equation}
\begin{example}
下面这个函数...
\begin{equation}
    f_1(x)=\frac{x+1}{x-1}
\end{equation}
..是一个函数
\begin{equation}
    f_2(x)=\frac{x^2}{1+x^3}
\end{equation}
\begin{equation}
    f_3(x)=\frac{3+ x^2}{1-x^3}
\end{equation}
\end{example}
\end{document}
```

[在 Overleaf 中打开此 `\counterwithin` Overleaf 中的示例](https://www.overleaf.com/docs?engine=pdflatex\&snip_name=Example+of+using+counterwithin\&snip=%5Cdocumentclass%7Barticle%7D%0A%5Ccounterwithin%7Bequation%7D%7Bsection%7D%0A%5Cnewcounter%7Bexample%7D%0A%5Ccounterwithin%2A%7Bexample%7D%7Bsection%7D%0A%5Cnewenvironment%7Bexample%7D%5B1%5D%5B%5D%7B%25%0A%5Cstepcounter%7Bexample%7D%25%0A%5Cpar%5Cvspace%7B5pt%7D%5Cnoindent%0A%5Cfbox%7B%5Ctextbf%7BExample%7E%5Cthesection.%5Ctheexample%7D%7D%25%0A%5Chrulefill%5Cpar%5Cvspace%7B10pt%7D%5Cnoindent%5Crmfamily%7D%25%0A%7B%5Cpar%5Cnoindent%5Chrulefill%5Cvrule+width10pt+height2pt+depth2pt%5Cpar%7D%0A%5Cbegin%7Bdocument%7D%0A%5Csection%7BFirst+equation%7D%0ASome+introductory+text...%0A%5Cbegin%7Bexample%7D%0A%5Cbegin%7Bequation%7D%0A++++f%28x%29%3D%5Cfrac%7Bx%7D%7B1%2Bx%5E2%7D%0A%5Cend%7Bequation%7D%0A%5Cend%7Bexample%7D%0A%0A%5Csubsection%7BMore+detail%7D%0A%5Cbegin%7Bexample%7D%0AHere+we+discuss%0A%5Cbegin%7Bequation%7D%0A++++f%28x%29%3D%5Cfrac%7Bx%2B1%7D%7Bx-1%7D%0A%5Cend%7Bequation%7D%0A...+but+don%27t+say+anything%0A%5Cend%7Bexample%7D%0A%0A%5Csubsubsection%7BEven+more+detail%7D%0A%5Cbegin%7Bexample%7D%0A%5Cbegin%7Bequation%7D%0A++++f%28x%29%3D%5Cfrac%7Bx%5E2%7D%7B1%2Bx%5E3%7D%0A%5Cend%7Bequation%7D%0A%5Cbegin%7Bequation%7D%0A++++f%28x%2B%5Cdelta+x%29%3D%5Cfrac%7B%28x%2B%5Cdelta+x%29%5E2%7D%7B1%2B%28x%2B%5Cdelta+x%29%5E3%7D%0A%5Cend%7Bequation%7D%0A%5Cend%7Bexample%7D%0A%0A%5Csection%7BThird+equation%7D%0A%5Cbegin%7Bexample%7D%0AThe+following+function...%0A%5Cbegin%7Bequation%7D%0A++++f_1%28x%29%3D%5Cfrac%7Bx%2B1%7D%7Bx-1%7D%0A%5Cend%7Bequation%7D%0A..is+a+function%0A%5Cbegin%7Bequation%7D%0A++++f_2%28x%29%3D%5Cfrac%7Bx%5E2%7D%7B1%2Bx%5E3%7D%0A%5Cend%7Bequation%7D%0A%5Cbegin%7Bequation%7D%0A++++f_3%28x%29%3D%5Cfrac%7B3%2B+x%5E2%7D%7B1-x%5E3%7D%0A%5Cend%7Bequation%7D%0A%5Cend%7Bexample%7D%0A%5Cend%7Bdocument%7D)

此示例生成以下输出：

![使用 \counterwithin 命令](/files/d5de8a58584df2e1a9d5fdd51312da68cda4a4eb)

**代码摘要**

* `\newcounter{example}`：这会创建一个供我们环境使用的新计数器，也称为 `示例`
* `\counterwithin*{example}{section}`：这会将我们的 `示例` 计数器与 `section` 在……中使用的计数器连接起来 `\section` 命令：每当我们发出一个 `\section` 命令时， `示例` 计数器都会被重置为零。注意我们使用了带星号的版本 `\counterwithin*` 以避免重新定义 `\theexample`
* 接下来，我们创建一个同样称为 `示例`的新环境。在该环境中，我们使用 `\stepcounter{example}` 来递增该环境的计数器。还要注意我们写了 `\textbf{Example~\thesection.\theexample}` 来输出 **示例** `<节编号>.<示例编号>`

```latex
\newenvironment{example}[1][]{%
\stepcounter{example}%
\par\vspace{5pt}\noindent
\fbox{\textbf{Example~\thesection.\theexample}}%
\hrulefill\par\vspace{10pt}\noindent\rmfamily}%
{\par\noindent\hrulefill\vrule width10pt height2pt depth2pt}
```

**\counterwithout{somecounter}{anothercounter}**

`\counterwithout{*somecounter*}{*anothercounter*}` 移除……之间的关联 `*somecounter*` 和 `*anothercounter*` 使它们彼此独立。对于任意一对计数器，你都可以在使用 `\counterwithout` 和 `\counterwithin`之间切换，下面的示例展示了 `示例` 和 `section` 这些计数器的情况——你可以使用代码下方提供的链接在 Overleaf 中打开此示例。

```latex
\section{First equation}
\begin{example}
\begin{equation}
    f(x)=\frac{x}{1+x^2}
\end{equation}
\end{example}

\subsection{Second equation}
\begin{example}
\begin{equation}
    f(x)=\frac{x+1}{x-1}
\end{equation}
\end{example}
\vspace{6pt}\noindent 注意 \texttt{example} 计数器在第 \ref{sec:n0} 节开始时是如何被重置的。
\section{Third equation}
\label{sec:n0}
\begin{example}
\begin{equation}
    f(x)=\frac{x+1}{x-1}
\end{equation}
\end{example}
\vspace{6pt}\noindent 在这里，我们写入了 \verb|\counterwithout{example}{section}|，因此 \texttt{example} 不再在每一节开始时重置。在第 \ref{sec:n1} 节和第 \ref{sec:n2} 节中，\texttt{example} 计数器会继续递增。 \counterwithout{example}{section}
\section{Fourth equation}
\label{sec:n1}
\begin{example}
\begin{equation}
    f(x)=\frac{x^2+x^3}{1+x^3}
\end{equation}
\end{example}
\section{Fifth equation}
\label{sec:n2}
\begin{example}
\begin{equation}
    f(x,k)=\frac{x^2-x^k}{1+x^3}
\end{equation}
\end{example}
```

[在 Overleaf 中打开此 `\counterwithout` Overleaf 中的示例](<https://www.overleaf.com/docs?engine=pdflatex\&snip_name=Example+of+using+counterwithout\&snip=\documentclass{article}&#xA;\counterwithin{equation}{section}&#xA;\newcounter{example}&#xA;\counterwithin*{example}{section}&#xA;\newenvironment{example}\[1]\[]{%&#xA;\stepcounter{example}%&#xA;\par\vspace{3pt}\noindent&#xA;\fbox{\textbf{Example~\thesection.\theexample}}%&#xA;\hrulefill\par\vspace{3pt}\noindent\rmfamily}%&#xA;{\par\noindent\hrulefill\vrule+width10pt+height2pt+depth2pt\par}&#xA;\begin{document}&#xA;\section{First+equation}&#xA;\begin{example}&#xA;\begin{equation}&#xA;++++f(x)=\frac{x}{1+x^2}&#xA;\end{equation}&#xA;\end{example}&#xA;&#xA;\subsection{Second+equation}&#xA;\begin{example}&#xA;\begin{equation}&#xA;++++f(x)=\frac{x+1}{x-1}&#xA;\end{equation}&#xA;\end{example}&#xA;\vspace{6pt}\noindent+Note+how+the+\texttt{example}+counter+is+reset+at+the+start+Section+\ref{sec:n0}.+&#xA;\section{Third+equation}&#xA;\label{sec:n0}&#xA;\begin{example}&#xA;\begin{equation}&#xA;++++f(x)=\frac{x+1}{x-1}&#xA;\end{equation}&#xA;\end{example}&#xA;\vspace{6pt}\noindent+Here,+we+wrote+\verb|\counterwithout{example}{section}|+so+that+\texttt{example}+is+no+longer+reset+at+the+start+of+a+section.+In+Sections+\ref{sec:n1}+and+\ref{sec:n2}+the+\texttt{example}+counter+keeps+increasing.+\counterwithout{example}{section}&#xA;\section{Fourth+equation}&#xA;\label{sec:n1}&#xA;\begin{example}&#xA;\begin{equation}&#xA;++++f(x)=\frac{x^2+x^3}{1+x^3}&#xA;\end{equation}&#xA;\end{example}&#xA;\section{Fifth+equation}&#xA;\label{sec:n2}&#xA;\begin{example}&#xA;\begin{equation}&#xA;++++f(x,k)=\frac{x^2-x^k}{1+x^3}&#xA;\end{equation}&#xA;\end{example}&#xA;\end{document}>)

此示例生成以下输出：

![使用 counterwithout 命令](/files/c0f74106e4c9a205afbac0bf7892556b51f10cdd)

## 示例

### enumerate

该 `enumerate` list 环境使用四个 *计数器* 变量，用于跟踪每一层当前的标签值：

|        |                       |
| ------ | --------------------- |
| **层级** | **`enumerate`** 计数器变量 |
| 第 1 层  | `enumi`               |
| 第 2 层  | `enumii`              |
| 第 3 层  | `enumiii`             |
| 第 4 层  | `enumiv`              |

这些计数器可以使用 `\setcounter` 命令进行更改。请参见下面的示例——这不一定是最佳解决方案（参见 [Overleaf 列表](/latex/zh-cn/latex-ji-chu/04-lists.md) 文章以了解更多信息）：

```latex
这个示例展示了更改列表编号的一种方法；这里，通过将 \texttt{enumi} 计数器的值设为 3，使列表编号从 4 开始（它会被 \verb|\item| 命令递增）：

\begin{enumerate}
\setcounter{enumi}{3}
\item 某项。
\item 另一项内容。
\item 另一个元素。
\item 列表中的最后一项。
\end{enumerate}
```

[在 Overleaf 中打开此示例](https://www.overleaf.com/docs?engine=pdflatex\&snip_name=Modifying+an+enumerate+counter\&snip=%5Cdocumentclass%7Barticle%7D%0A%5Cbegin%7Bdocument%7D%0A%5Csection%7BIntroduction%7D%0AThis+example+shows+one+way+to+change+the+numbering+of+a+list%3B+here%2C+changing+the+value+of+the+%5Ctexttt%7Benumi%7D+counter+to+start+the+list+numbering+at+4+%28it+is+incremented+by+the+%5Cverb%7C%5Citem%7C+command%29%3A%0A%0A%5Cbegin%7Benumerate%7D%0A%5Csetcounter%7Benumi%7D%7B3%7D%0A%5Citem+Something.%0A%5Citem+Something+else.%0A%5Citem+Another+element.%0A%5Citem+The+last+item+in+the+list.%0A%5Cend%7Benumerate%7D%0A%5Cend%7Bdocument%7D)

此示例生成以下输出：

![修改 enumerate 计数器](/files/b955bd95b8ffce7d227c59e3a03310320fc0b06b)

## LaTeX 中的默认计数器

| 用法                | 名称                                                                  |
| ----------------- | ------------------------------------------------------------------- |
| 用于文档结构            | <p>- 部分<br>- 章节<br>- 节<br>- 小节<br>- 子小节<br>- 段落<br>- 子段落<br>- 页</p> |
| 用于浮动体             | <p>- 方程<br>- 图<br>- 表</p>                                           |
| 用于脚注              | <p>- 脚注<br>- mpfootnote</p>                                         |
| 用于 `enumerate` 环境 | <p>- enumi<br>- enumii<br>- enumiii<br>- enumiv</p>                 |

## 进一步阅读

更多信息请参见：

* [环境](/latex/zh-cn/ming-ling/02-environments.md)
* [命令](/latex/zh-cn/ming-ling/01-commands.md)
* [列表](/latex/zh-cn/latex-ji-chu/04-lists.md)
* [页码编号](/latex/zh-cn/ge-shi-hua/03-page-numbering.md)
* [章节和小节](/latex/zh-cn/wen-dang-jie-gou/01-sections-and-chapters.md)
* [数学表达式](/latex/zh-cn/shu-xue/01-mathematical-expressions.md)
* [插入图片](/latex/zh-cn/geng-duo-zhu-ti/27-inserting-images.md)
* [表格](/latex/zh-cn/tu-biao-he-biao-ge/01-tables.md)
* [在 LaTeX 中排版考试](/latex/zh-cn/te-ding-ling-yu/09-typesetting-exams-in-latex.md)
* [编写你自己的宏包](/latex/zh-cn/lei-wen-jian/03-writing-your-own-package.md)
* [编写你自己的类](/latex/zh-cn/lei-wen-jian/04-writing-your-own-class.md)
* [LaTeX2ε 不那么简短的介绍](http://www.ctan.org/tex-archive/info/lshort/)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://overleaf-pro.ayaka.space/latex/zh-cn/ge-shi-hua/10-counters.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
