计算文档后面的项目数

计算文档后面的项目数

问题很简单:如何使我的计数器(\themycounter)的输出显示以下内容6

\documentclass{article}
\newcounter{mycounter}
\newcommand{\myitem}{\refstepcounter{mycounter}}
\begin{document}
I have some reason to tally up some items here\myitem \myitem \myitem.
But how many items are there in total in this document?
Are there {\themycounter} items?
Surely there are more since I am tallying up some more items now\myitem \myitem \myitem.
\end{document}

我确信答案不需要像显示计数器的后续值(这就是我冒昧在这里提问的原因)。

答案1

您可以使用totcount包;您创建并注册计数器\newtotcounter{<counter>}然后使用\total{<counter>}(需要两到三次运行):

\documentclass{article}
\usepackage{totcount}
\newtotcounter{mycounter}
\newcommand{\myitem}{\refstepcounter{mycounter}}

\begin{document}
I have some reason to tally up some items here\myitem \myitem \myitem.
But how many items are there in total in this document?
Are there {\themycounter} items? No, there are \total{mycounter}, since I am tallying up some more items now\myitem \myitem \myitem.
\end{document}

在此处输入图片描述

答案2

egreg回答以下问题问题你也链接了:(另请参阅下一个更好的变体)

\documentclass{article}
\newcounter{mycounter}
\newcommand{\myitem}{\refstepcounter{mycounter}}
\begin{document}
I have some reason to tally up some items here\myitem \myitem \myitem.
But how many items are there in total in this document?
Are there \ref{finalmyitem} items?
Surely there are more since I am tallying up some more items now\myitem \myitem \myitem\label{finalmyitem}.
\end{document}

此方法(源自评论)避免了必须 \label在最后一个之后手动添加\myitem

\documentclass{article}
\newcounter{mycounter}

%%   \newcommand{\myitem}{\refstepcounter{mycounter}}
%% \AtEndDocument{\addtocounter{mycounter}{-1}\myitem\label{finalmyitem}}

% again a variant:
\newcommand{\myitem}{\stepcounter{mycounter}}
\AtEndDocument{\addtocounter{mycounter}{-1}\refstepcounter{mycounter}\label{finalmyitem}}

\begin{document}
I have some reason to tally up some items here\myitem \myitem \myitem.
But how many items are there in total in this document?
Are there {\ref{finalmyitem}} items?
Surely there are more since I am tallying up some more items now\myitem \myitem \myitem.
\end{document}

6 项

相关内容