算法列表中出现错误,.loa 文件中未定义控制序列

算法列表中出现错误,.loa 文件中未定义控制序列

我正在尝试用 LaTeX 编写伪代码,并希望在 中列出算法\listofalgorithms。使用以下代码,我可以在 pdf 中生成伪代码,并且算法也会在 中列出\listofalgorithms。但是链接无法正常工作。当我单击算法列表中的行时,它会将我链接到文档的开头,而不是链接到算法。

编译时产生的错误和代码如下。该算法取自算法打包用户文档。

\documentclass[a4paper,12pt]{report}
\usepackage{algorithm, algpseudocode}
\usepackage{hyperref}

\begin{document}
    \begin{algorithm}
    \caption{Euclid’s algorithm}\label{euclid}
    \begin{algorithmic}[1]
    \Procedure{Euclid}{$a,b$}\Comment{The g.c.d. of a and b}
    \State $r\gets a\bmod b$
    \While{$r\not=0$}\Comment{We have the answer if r is 0}
    \State $a\gets b$
    \State $b\gets r$
    \State $r\gets a\bmod b$
    \EndWhile\label{euclidendwhile}
    \State \textbf{return} $b$\Comment{The gcd is b}
    \EndProcedure
    \end{algorithmic}
    \end{algorithm}

    \listofalgorithms
 \end{document}

当我编译该程序时,出现以下错误:

./report.loa:1: Undefined control sequence. [...aces Euclid}}{4}{algorithm.\theHalgorithm }]

在 report.loa 文件中我写了以下行

\contentsline {algorithm}{\numberline {1}{\ignorespaces Euclid’s algorithm}}{4}{algorithm.\theHalgorithm }

我使用 latexmk 版本 4.43a,作为编辑器,我使用带有 LaTeXTools 包的 sublime。

答案1

我终于找到了问题的答案。它列在http://www.macfreek.nl/memory/LaTeX_package_conflicts#Hyperref_and_Algorithmic在 Hyperref 和算法部分下。所以我想与你分享一下。

正如该链接所引用的:

“如果在 hyperref 之后加载算法,则 .aux 文件中的任何 \label{alg:myalgorithm} 语句最终都会出现错误(它包含虚假的 \theAlgorithm 语句)。如果第二次运行 latex(当它包含有错误的 aux 文件时),则会导致上述错误。”

显然,当所包含包的顺序改变时,错误就会消失。因此,如果您在算法 algpseudocode 包之前加载 hyperref 包,则代码将按预期运行,不会出现任何错误。

\documentclass[a4paper,12pt]{report}
% hyperref package need to be loaded before the algorithm package
\usepackage{hyperref}
\usepackage{algorithm, algpseudocode}

\begin{document}
    \begin{algorithm}
    \caption{Euclid’s algorithm}\label{euclid}
    \begin{algorithmic}[1]
    \Procedure{Euclid}{$a,b$}\Comment{The g.c.d. of a and b}
    \State $r\gets a\bmod b$
    \While{$r\not=0$}\Comment{We have the answer if r is 0}
    \State $a\gets b$
    \State $b\gets r$
    \State $r\gets a\bmod b$
    \EndWhile\label{euclidendwhile}
    \State \textbf{return} $b$\Comment{The gcd is b}
    \EndProcedure
    \end{algorithmic}
    \end{algorithm}

    \listofalgorithms
\end{document}

相关内容