将行号添加到 algorithm2e

将行号添加到 algorithm2e

如何为我的算法添加行号?我想在算法行的前面写上行号。如何使用 来获取它\usepackage[ruled]{algorithm2e}

代码:

\documentclass{article}
\usepackage[ruled]{algorithm2e}
\renewcommand{\baselinestretch}{1.5}

\usepackage{listings}
\usepackage{blindtext}
\begin{document}
\blindtext

\vspace{1cm}

\begin{algorithm}[H]
   \SetAlgoLined
   \KwData{$next\_id, speed,stop\_distance, mac$}
   \KwResult{Find the initializer. }
   int $next\_id1$ = find a  record with $speed > 30$ \\ for this $mac$ in the next table;\\
   int $next\_id2$ = find record with $speed <7$ and \\ $stop\_distance < 60$ for this mac in the next table;\\
   \If{$next\_id1 < next\_id2$}{
      find the related $stop\_name$ for this mac;\\
      return  $stop\_name$;
   }
   \caption{Algorithm to find intializer.}
\end{algorithm}
\vspace{1cm}
\begin{lstlisting}[caption = {MYSQL query to find the initializer.}, label={lst: initializer}]
SELECT speed, stop_name
from next
where stop_distance < 60 and speed < 7  
and mac = ? and next_id > ?  LIMIT  1
\end{lstlisting}

\clearpage
\end{document} 

答案1

linesnumbered要对所有行进行编号,请在加载时添加包选项或\LinesNumbered在序言/文档中的某处执行。

在此处输入图片描述

\documentclass{article}
\usepackage[ruled,linesnumbered]{algorithm2e}
\newcommand{\var}{\texttt}

\begin{document}

\vspace{1cm}

\begin{algorithm}[H]
  \SetAlgoLined
  \KwData{$\var{next\_id}$, $\var{speed}$, $\var{stop\_distance}$, $\var{mac}$}
  \KwResult{Find the initializer. }
  int $\var{next\_id1}$ = find a  record with $\var{speed} > 30$ 
   for this $\var{mac}$ in the next table \;
  int $\var{next\_id2}$ = find record with $\var{speed} < 7$ and 
   $\var{stop\_distance} < 60$ for this $\var{mac}$ in the next table \;
  \If{$\var{next\_id1} < \var{next\_id2}$}{
    find the related $\var{stop\_name}$ for this mac \;
    return $\var{stop\_name}$ \;
  }
  \caption{Algorithm to find intializer.}
\end{algorithm}

\end{document}

对于较长的行的缩进,您可以手动将其拆分,并使用中描述的技术插入缩进换行符algorithm2e

答案2

这是开箱即用的(使用最新的 TeX 发行版)

\documentclass{article}
\usepackage[ruled]{algorithm2e}
\renewcommand{\baselinestretch}{1.5}

\usepackage{listings}
\usepackage{blindtext}
\begin{document}
\blindtext

 %\vspace{1cm}

\SetNlSty{texttt}{(}{)}
\begin{algorithm}[H]
\SetAlgoLined
\nl   \KwData{$next\_id, speed,stop\_distance, mac$}
\nl   \KwResult{Find the initializer. }
\nl   int $next\_id1$ = find a  record with $speed > 30$ \\ for this $mac$ in the next table;\\
\nl   int $next\_id2$ = find record with $speed <7$ and \\ $stop\_distance < 60$ for this mac in the next table;\\
\nl   \If{$next\_id1 < next\_id2$}{
\nl      find the related $stop\_name$ for this mac;\\
\nl      return  $stop\_name$;
   }
   \caption{Algorithm to find intializer.}
\end{algorithm}
\vspace{1cm}
\begin{lstlisting}[caption = {MYSQL query to find the initializer.}, label={lst: initializer}]
SELECT speed, stop_name
from next
where stop_distance < 60 and speed < 7  
and mac = ? and next_id > ?  LIMIT  1
\end{lstlisting}

\clearpage
\end{document} 

在此处输入图片描述

相关内容