我想在我的文档中包含多个带有章节的列表。我还希望每个列表都有标签,例如清单 2.1其中 2 是部分编号,1 是该部分中给定列表的编号。到目前为止,我能够生成以下代码:
\documentclass[a4paper]{article}
\usepackage{listings}
\lstset{frame=Trbl,numbers=left}
\begin{document}
\renewcommand{\thelstlisting}{\thesection.\arabic{lstlisting}}
\section{Introduction}
First listing is numbered properly.
\begin{lstlisting}[caption=First listing]
Lorem
Ipsum
\end{lstlisting}
Second is correct too.
\begin{lstlisting}[caption=Second listing]
Dolor sit Amet
\end{lstlisting}
So far, all listings in one section are correct.
\section{First problem}
When a new section begins, the counter doesn't get reset.
\begin{lstlisting}[caption=First listing in second section]
consectetur
adispicing
elit
\end{lstlisting}
\end{document}
但这会产生以下结果:
如何在每个部分开始后重置计数器?
答案1
解决方案是包含包chngcntr
并放置\counterwithin{lstlisting}{section}
在后面\begin{document}
。完整的代码如下
\documentclass[a4paper]{article}
\usepackage{listings,chngcntr}
\lstset{frame=Trbl,numbers=left}
\usepackage{amsmath}
\begin{document}
\counterwithin{lstlisting}{section}
\section{Introduction}
First listing is numbered properly.
\begin{lstlisting}[caption=First listing]
Lorem
Ipsum
\end{lstlisting}
Second is correct too.
\begin{lstlisting}[caption=Second listing]
Dolor sit Amet
\end{lstlisting}
So far, all listings in one section are correct.
\section{First problem}
When a new section begins, the counter doesn't get reset.
\begin{lstlisting}[caption=First listing in second section]
consectetur
adispicing
elit
\end{lstlisting}
\end{document}
产生所需的输出: