![缺失数字,使用 amsmath 和 calc 视为零](https://linux22.com/image/309651/%E7%BC%BA%E5%A4%B1%E6%95%B0%E5%AD%97%EF%BC%8C%E4%BD%BF%E7%94%A8%20amsmath%20%E5%92%8C%20calc%20%E8%A7%86%E4%B8%BA%E9%9B%B6.png)
这个简单的代码产生
"Missing number, treated as zero"
\documentclass{article}
\newcounter{test}
\newcounter{testtwo}
\usepackage{calc}
\usepackage{amsmath}
\begin{document}
\addtocounter{test}{\value{testtwo}*\value{testtwo}}
\end{document}
在下列情况下编译良好:
- 没有
amsmath
- 何时
calc
加载amsmath
- 使用
\setcounter
而不是\addtocounter
这里发生了什么事?
如果加载了一个类calc
,而我们需要amsmath
,我们该怎么办?我知道在这种情况下,解决方案是amsmath
在类之前加载\RequirePackage
。两者之间是否有其他解决方法\usepackage
?
答案1
无论首先加载哪个包,更快的解决方法是使用\numexpr
扩展e-tex
(现在基本上任何 TeX 发行版都可以使用)。
它在计算之前将计算值扩展\addtocounter
在以下 MWE 中,结果正如预期的那样,100
\documentclass{article}
\newcounter{test}
\newcounter{testtwo}
\usepackage{calc}
\usepackage{amsmath}
\begin{document}
\setcounter{testtwo}{10}
\addtocounter{test}{\numexpr\value{testtwo}*\value{testtwo}}
\thetest
\end{document}
答案2
由于calc
重新定义了\setcounter
,\stepcounter
并且\addtocounter
,如果您想保留设置,唯一的方法就是在加载后重新声明这些定义amsmath
。
也就是说,在序言中,在后面添加以下几行\usepackage{amsmath}
\makeatletter
\def\setcounter#1#2{\@ifundefined{c@#1}{\@nocounterr{#1}}%
{\calc@assign@count{\global\csname c@#1\endcsname}{#2}}}
\def\addtocounter#1#2{\@ifundefined{c@#1}{\@nocounterr{#1}}%
{\calc@assign@count{\global\advance\csname c@#1\endcsname}{#2}}}%
\def\stepcounter#1{\@ifundefined {c@#1}%
{\@nocounterr {#1}}%
{\global\advance\csname c@#1\endcsname \@ne
\begingroup
\let\@elt\@stpelt \csname cl@#1\endcsname
\endgroup}}%
\@ifpackageloaded{amstext}{%
\expandafter\def\expandafter\stepcounter
\expandafter#\expandafter1\expandafter{%
\expandafter\iffirstchoice@\stepcounter{#1}\fi
}
\expandafter\def\expandafter\addtocounter
\expandafter#\expandafter1\expandafter#\expandafter2\expandafter{%
\expandafter\iffirstchoice@\addtocounter{#1}{#2}\fi
}
}{}
\makeatother
梅威瑟:
\documentclass{article}
\newcounter{test}
\newcounter{testtwo}
\usepackage{calc}
\usepackage{amsmath}
\makeatletter
\def\setcounter#1#2{\@ifundefined{c@#1}{\@nocounterr{#1}}%
{\calc@assign@count{\global\csname c@#1\endcsname}{#2}}}
\def\addtocounter#1#2{\@ifundefined{c@#1}{\@nocounterr{#1}}%
{\calc@assign@count{\global\advance\csname c@#1\endcsname}{#2}}}%
\def\stepcounter#1{\@ifundefined {c@#1}%
{\@nocounterr {#1}}%
{\global\advance\csname c@#1\endcsname \@ne
\begingroup
\let\@elt\@stpelt \csname cl@#1\endcsname
\endgroup}}%
\@ifpackageloaded{amstext}{%
\expandafter\def\expandafter\stepcounter
\expandafter#\expandafter1\expandafter{%
\expandafter\iffirstchoice@\stepcounter{#1}\fi
}
\expandafter\def\expandafter\addtocounter
\expandafter#\expandafter1\expandafter#\expandafter2\expandafter{%
\expandafter\iffirstchoice@\addtocounter{#1}{#2}\fi
}
}{}
\makeatother
\begin{document}
\setcounter{testtwo}{6}
\addtocounter{test}{\value{testtwo}*\value{testtwo}}
\the\value{test}
\end{document}
输出