> 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-tw/ge-shi-hua/10-counters.md).

# 計數器

## LaTeX 計數器簡介

基於 LaTeX 的排版是一種專門化的程式設計形式：你使用排版語言（LaTeX 指令）來提供「指示」，其結果是一個輸出：以 PDF 檔案形式呈現的編譯後 LaTeX 文件。和任何程式設計工作一樣，你很可能會需要 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}|\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{範例~\theexample. #1} \rmfamily}{\medskip}

\begin{document}
\section{三個範例}
\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{另一節}
我們剛開始一個新章節，這表示 \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` 範例](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-tw/zhi-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 Error: Counter too large.`

#### \Alph{somecounter}

將 `*somecounter*` 輸出為大寫字母，其中 A=1、B=2、C=3……

* **注意**: `*somecounter*` 必須在範圍 `1` $$\leq$$ `*somecounter*` $$\leq$$ `26`內，否則會觸發錯誤 `! LaTeX Error: Counter too large.`

#### \fnsymbol{somecounter}

將 `*somecounter*` 輸出為註腳符號，其中 1 =∗、2 =†……

* **注意**: `*somecounter*` 必須在範圍 `1` $$\leq$$ `*somecounter*` $$\leq$$ `9`內，否則會觸發錯誤 `! LaTeX Error: Counter too large.`

|                    |                        |
| ------------------ | ---------------------- |
| 值為 `*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/529bedf4ec614ab186a60fd2fa4b5d1450a02021)

#### \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 你可以用 \verb|\thefirst| 輸出 \texttt{first} 的值：\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/2e5da56959b7fbf359bc4f004f2c89742e5b1016)

### 其他計數器指令

這裡說明以下指令 `\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*` 的值，而是輸出 `<另一個計數器的值>**.**<somecounter 的值>`。星號形式（`\counterwithin*{somecounter}{anothercounter}`）不會重新定義 `*somecounter*`的列印格式，如下列範例所示——請選擇程式碼下方的連結，在 Overleaf 中開啟它：

```latex
\documentclass{article}
\begin{document}
\section{一個簡短範例}
\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` 範例](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/82f002449619dbb64ee475d57d52cc275332630c)

你可以將 `\counterwithin` 與 LaTeX 提供的標準計數器一起使用，例如：

* `section`：由 `\section` 指令
* `equation` 使用的 `equation` 環境

，或與你自行建立的計數器一起使用。

**\counterwithin 和 \counterwithin\* 的範例**

以下程式碼提供了一個更完整的 \counterwithin\* 使用範例；請選擇程式碼下方的連結，在 Overleaf 中開啟： `\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{範例~\thesection.\theexample}}%
\hrulefill\par\vspace{10pt}\noindent\rmfamily}%
{\par\noindent\hrulefill\vrule width10pt height2pt depth2pt\par}
\begin{document}
\section{第一個方程式}
一些導言文字...
\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{第三個方程式}
\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` 範例](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/20d29143f5ee47ed5e69461797f165a028cbe6af)

**程式碼摘要**

* `\newcounter{example}`：這會建立一個供我們環境使用的新計數器，也稱為 `範例`
* `\counterwithin*{example}{section}`：這會將我們的 `範例` 計數器與 `section` 命令內使用的計數器連結起來：每次我們發出 `\section` 命令時， `\section` 計數器都會被重設為零。請注意，我們使用了星號版本 `範例` ，以避免重新定義 `\counterwithin*` 。接著，我們建立一個同樣稱為 `\theexample`
* 的新環境。在那個環境中，我們使用 `範例`。在那個環境中我們使用 `\stepcounter{example}` 來遞增環境的計數器。也請注意我們寫入 `\textbf{範例~\thesection.\theexample}` 來輸出 **範例** `<章節編號>.<範例編號>`

```latex
\newenvironment{example}[1][]{%
\stepcounter{example}%
\par\vspace{5pt}\noindent
\fbox{\textbf{範例~\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` 之間切換，如下列範例所示，適用於

```latex
\section{第一個方程式}
\begin{example}
\begin{equation}
    f(x)=\frac{x}{1+x^2}
\end{equation}
\end{example}

這些計數器——你可以使用程式碼下方提供的連結在 Overleaf 中開啟這個範例。\subsection{第二個方程式}
\begin{example}
\begin{equation}
    f(x)=\frac{x+1}{x-1}
\end{equation}
\end{example}
\vspace{6pt}\noindent 請注意 \texttt{example} 計數器是在第 \ref{sec:n0} 節開頭重設的。
\section{第三個方程式}
\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}
```

[在 Overleaf 中開啟這個 `\counterwithout` 範例](<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/262b003a6a31c7041bccbeeef8c7c353e499d67a)

## 範例

### enumerate

該 `enumerate` 列表環境使用四個 *計數器* 變數，它們追蹤每一層目前的標籤值：

|        |                       |
| ------ | --------------------- |
| **層級** | **`enumerate`** 計數器變數 |
| 第 1 層  | `enumi`               |
| 第 2 層  | `enumii`              |
| 第 3 層  | `enumiii`             |
| 第 4 層  | `enumiv`              |

這些計數器可以使用 `\setcounter` 指令來變更。請參見下面的範例——這未必是最佳解法（請參見 [Overleaf 列出](/latex/zh-tw/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/6424cc5ddfecdda3893890985e288d3ff19571ec)

## 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-tw/zhi-ling/02-environments.md)
* [命令](/latex/zh-tw/zhi-ling/01-commands.md)
* [清單](/latex/zh-tw/latex-ji-chu/04-lists.md)
* [頁碼編號](/latex/zh-tw/ge-shi-hua/03-page-numbering.md)
* [章節](/latex/zh-tw/wen-jian-jie-gou/01-sections-and-chapters.md)
* [數學表達式](/latex/zh-tw/shu-xue/01-mathematical-expressions.md)
* [插入圖片](/latex/zh-tw/geng-duo-zhu-ti/27-inserting-images.md)
* [表格](/latex/zh-tw/tu-biao-yu-biao-ge/01-tables.md)
* [在 LaTeX 中排版考試試卷](/latex/zh-tw/te-ding-ling-yu/09-typesetting-exams-in-latex.md)
* [撰寫你自己的套件](/latex/zh-tw/lei-bie-dang/03-writing-your-own-package.md)
* [撰寫自己的類別](/latex/zh-tw/lei-bie-dang/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-tw/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.
