> For the complete documentation index, see [llms.txt](https://ayakaleaf-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://ayakaleaf-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*`的命令。下面给出了一个示例，你可以通过所提供的链接，在 Overleaf 中以完整文档形式打开这段 LaTeX 代码：

```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 中](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} % decreases somecounter by 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}|\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}
\section{Three examples}
\begin{example}
在这个第一个示例中创建一个标签 \verb|\label{ex:1}|\label{ex:1}。这是第一个示例。每个新的 \verb|\section| 开始时，\texttt{example} 计数器都会被重置。
\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}
```

[打开此 `\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]`：创建一个名为 `示例` 的新计数器，每次 `节` 计数器增加时都会将其重置为 0。你可以用任何其他计数器替代 `节` ，或者如果你不希望计数器自动重置，也可以省略该参数。
* `\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`.

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

\newcounter{first}
\newcounter{second}

\noindent 稍后在代码中的某个地方，你给它们赋值：
\begin{verbatim}
\setcounter{first}{100}
\setcounter{second}{50}
\end{verbatim}

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

\noindent 在某个时候，我们可能想把计数器 \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}
```

[打开此 `\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` 命令
* `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{More detail}
\begin{example}
这里我们讨论
\begin{equation}
    f(x)=\frac{x+1}{x-1}
\end{equation}
... 但不说任何事情
\end{example}

\subsubsection{Even more detail}
\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}
```

[打开此 `\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` 命令关联起来：每次我们发出一个 `示例` 命令时， `\counterwithin*` 计数器都会被重置为零。注意我们使用了带星号的版本 `\theexample`
* 接下来，我们还创建一个新的环境，也称为 `示例`。在该环境中我们使用 `\stepcounter{example}` 来递增该环境的计数器。还要注意，我们写 `\textbf{Example~\thesection.\theexample}` 来输出 **示例** `<section number>.<example number>`

```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`，正如下方示例对 `示例` 和 `节` 计数器所示——你可以使用代码下方提供的链接在 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{第四个公式}
\label{sec:n1}
\begin{example}
\begin{equation}
    f(x)=\frac{x^2+x^3}{1+x^3}
\end{equation}
\end{example}
\section{第五个公式}
\label{sec:n2}
\begin{example}
\begin{equation}
    f(x,k)=\frac{x^2-x^k}{1+x^3}
\end{equation}
\end{example}
```

[打开此 `\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` 列表环境使用四个 *计数器* 变量，用于跟踪每一层当前的标签值：

|        |                       |
| ------ | --------------------- |
| **级别** | **`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)

此示例生成如下输出：

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

## LaTeX 中的默认计数器

| 用法                | 名称                                                                                                                    |
| ----------------- | --------------------------------------------------------------------------------------------------------------------- |
| 用于文档结构            | <p>- part<br>- chapter<br>- section<br>- subsection<br>- subsubsection<br>- paragraph<br>- subparagraph<br>- page</p> |
| 用于浮动体             | <p>- equation<br>- figure<br>- table</p>                                                                              |
| 用于脚注              | <p>- footnote<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-xing-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://ayakaleaf-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.
