如何在调用 \newcounter 或 \addtocounter 之前扩展计数器名称

如何在调用 \newcounter 或 \addtocounter 之前扩展计数器名称

我需要做以下事情

\newcounter{problem\theenumi}

显然,enumi会随时间而变化,但计数器名称必须立即修复!因此,例如,即使在\end{enumerate}我应该可以访问计数器之后problem1problem2我还是玩了,\expandafter但没有运气。我该怎么做?

答案1

以下是您可能想要的内容:

在此处输入图片描述

\documentclass{article}

\makeatletter
\newcommand{\pts}[1]{%
  \expandafter\providecommand\csname problem\theenumi\endcsname{0}% Define problem count
  \expandafter\expandafter\expandafter
    \renewcommand\expandafter\csname\expandafter problem\expandafter\theenumi\expandafter\endcsname\expandafter{%
    \number\numexpr\csname problem\theenumi\endcsname+#1% Sum points thus far
  }%
  (#1~points)%
}
\newcommand{\totalpoints}{Total points: \csname problem\theenumi\endcsname}% Print total points thus far
\makeatother

\begin{document}

\begin{enumerate}
  \item
  This is a question. \pts{5}

  This is another question. \pts{7}

  \totalpoints

  \item
  This is a new question. \pts{3}

  This is yet another question. \pts{12}

  A final question. \pts{23}

  \totalpoints
\end{enumerate}

Here is some discussion.

\begin{enumerate}
  \item
  This is a question. \pts{5}

  This is another question. \pts{7}

  This is a new question. \pts{3}

  This is yet another question. \pts{12}

  A final question. \pts{23}

  \totalpoints
\end{enumerate}

\end{document}

\pts{<points>}打印,而且还持续记录与问题/编号(<points> points)相关的点数。\item\theenumi

注意: 的定义\csname problem\theenumi\endcsname是首次调用的环境的本地定义\pts。因此,如果您有嵌套枚举,则应该将定义设为全局定义 - 代码中的微小更改,但这是必需的。

相关内容