使用 \labels 的值执行数学运算

使用 \labels 的值执行数学运算

我用\label它来索引多个环境中的项目数量。我希望对这些标签报告的数量进行求和。这是一个工作示例:

\documentclass{article}
\usepackage{enumitem} % Control enumerate's layout

\newenvironment{myenumerate}{
   \begin{enumerate}[label={\footnotesize\emph{item~\arabic*}},ref=\arabic*] % this is how enumitem lets you set different label and ref, see http://tex.stackexchange.com/questions/286879/customize-label-and-ref
   \setlength{\itemsep}{.1\itemsep}
   \setlength{\parskip}{.1\parskip}
}{\end{enumerate}}

\begin{document}

First environmnent:
\begin{myenumerate}
\item A
\item B
\item C \label{nitems1st}
\end{myenumerate}

Second environmnent:
\begin{myenumerate}
\item D
\item E \label{nitems2nd}
\end{myenumerate}

There are \ref{nitems1st} items in the first and \ref{nitems2nd} in the second. How can I compute the sum?

\end{document}

任何帮助都感激不尽。

答案1

您可以使用 LaTeX3\calcrefcount

在此处输入图片描述

\documentclass{article}
\usepackage{enumitem} % Control enumerate's layout
\usepackage{xparse,refcount}
\ExplSyntaxOn
  \cs_new_eq:NN \calc \fp_eval:n
\ExplSyntaxOff

\newlist{myenumerate}{enumerate}{1}
\setlist[myenumerate]{label={\footnotesize\emph{item~\arabic*}},ref=\arabic*}

\begin{document}

First environmnent:
\begin{myenumerate}
  \item A
  \item B
  \item C \label{nitems1st}
\end{myenumerate}

Second environmnent:
\begin{myenumerate}
  \item D
  \item E \label{nitems2nd}
\end{myenumerate}

There are \ref{nitems1st} items in the first and \ref{nitems2nd} in the second.

There are a total of \calc{\getrefnumber{nitems1st}+\getrefnumber{nitems2nd}} items.

\end{document}

如果你对总数的引用总是所有枚举,那么你可以使用xassoccnt计算列表环境项的每一步:

\documentclass{article}
\usepackage{enumitem} % Control enumerate's layout
\usepackage{xassoccnt}

\newlist{myenumerate}{enumerate}{1}
\setlist[myenumerate]{label={\footnotesize\emph{item~\arabic*}},ref=\arabic*}

\DeclareAssociatedCounters[autodefine=associated]{myenumeratei}{totalmyenum}

\begin{document}

First environmnent:
\begin{myenumerate}
  \item A
  \item B
  \item C \label{nitems1st}
\end{myenumerate}

Second environmnent:
\begin{myenumerate}
  \item D
  \item E \label{nitems2nd}
\end{myenumerate}

There are \ref{nitems1st} items in the first and \ref{nitems2nd} in the second.

There are a total of \thetotalmyenum{} items.

\end{document}

相关内容