在尝试回答问题时,我遇到了计数器问题,我需要一些帮助。这个想法是收集一些编号练习的答案,这样收集到的答案就可以在文档的稍后时间全部排版;我的方法是使用collect
打包来收集答案:
\documentclass{scrartcl}
\usepackage{collect}
\definecollection{answers}
\makeatletter
\newenvironment{answer}
{\@nameuse{collect}{answers}%
{\par\medskip\noindent\textbf{Answer to~\theexercise}}%
{\par}%
{}%
{}%
}
{\@nameuse{endcollect}}
\makeatother
\newcounter{exercise}
\newenvironment{ex}
{\refstepcounter{exercise}\par\noindent This is exercise~\theexercise}
{\par}
\begin{document}
\begin{ex}
\end{ex}
\begin{answer}
This is the answer to exercise 1 but it is numbered 3.
\end{answer}
\begin{ex}
\end{ex}
\begin{answer}
This is the answer to exercise 2 but it is numbered 3.
\end{answer}
\begin{ex}
\end{ex}
\begin{answer}
This is the answer to exercise 3 and it is numbered 3.
\end{answer}
\includecollection{answers}
\end{document}
然而,正如预期的那样,使用这种方法,所有答案都会收到与计数器最后一个值相对应的数字exercise
,而不是与它们对应的练习相关的数字(见图)。如何解决这个问题?
答案1
\theexercise
在进行写入之前您必须进行扩展:
\documentclass{scrartcl}
\usepackage{collect}
\definecollection{answers}
\newcommand\mycollect[1]{%
\collect{answers}
{\par\medskip\noindent\textbf{Answer to~#1}}
{\par}
{}{}%
}
\newenvironment{answer}
{\begingroup\edef\x{\endgroup\noexpand\mycollect{\theexercise}}\x}
{\endcollect}
\newcounter{exercise}
\newenvironment{ex}
{\refstepcounter{exercise}\par\noindent This is exercise~\theexercise}
{\par}
\begin{document}
\begin{ex}
\end{ex}
\begin{answer}
This is the answer to exercise 1 but it is numbered 3.
\end{answer}
\begin{ex}
\end{ex}
\begin{answer}
This is the answer to exercise 2 but it is numbered 3.
\end{answer}
\begin{ex}
\end{ex}
\begin{answer}
This is the answer to exercise 3 and it is numbered 3.
\end{answer}
\includecollection{answers}
\end{document}