我正在使用包algorithmicx
和algpseudocode
在论文中编写算法。指定注释比使用更方便、更美观algorithmic
。
但是我在使用“Require and Ensure”时遇到错误。行号总是错误的。
平均能量损失
\documentclass{article}
\usepackage{amsmath}
\usepackage{algorithm}
\usepackage{algpseudocode}
\begin{document}
\begin{algorithm}[ht]
\caption{My first algorithm}
\label{alg:algorithm1}
\begin{algorithmic}[1]
\Require~~\\
If there are multiple lines here, line's number will be wrong.\\
This error doesn't happen in package\{algorithmic\}
\Ensure~~\\
If I write $\setminus\setminus$ here, line's number will be wrong too.
\Statex
\If{$i = 1 \to n$} \Comment{This line's number should be 1}
\State ${\textit{HU}}_{i} \gets {\textit{NGU}}_{i} + {HU}_{i}$ \Comment{Comment}
\EndIf
\end{algorithmic}
\end{algorithm}
\end{document}
输出
问题
我需要在“Require”项中写两行。我该如何解决这个行数问题?
答案1
algorithmicx
将环境维护algorithmic
为列表。因此,您可以使用该\Statex
命令插入未编号的项目,类似于插入空行:
\documentclass{article}
\usepackage{algorithm,algpseudocode}% http://ctan.org/pkg/{algorithms,algorithmicx}
\begin{document}
\begin{algorithm}[ht]
\caption{My first algorithm}\label{alg:algorithm1}
\begin{algorithmic}[1]
\Require
\Statex If there are multiple lines here, line's number will be wrong.
\Statex This error doesn't happen in package \verb|algorithmic|.
\Ensure
\Statex If I write \verb|\\| here, line's number will be wrong too.
\Statex
\If{$i = 1 \to n$} \Comment{This line's number should be 1}
\State ${\textit{HU}}_{i} \gets {\textit{NGU}}_{i} + {HU}_{i}$ \Comment{Comment}
\EndIf
\end{algorithmic}
\end{algorithm}
\end{document}