我tabular
在里面用algorithm
环境(见下图)来对齐两列注释行。如果不使用表格,使用其他建议的方法很难完成此任务这里。
\documentclass{article}
\usepackage{amsmath}
\usepackage[vlined, ruled, noend]{algorithm2e}
\begin{document}
\begin{algorithm}
\LinesNumbered
\SetKwInOut{Input}{Input}
\SetKwInOut{Output}{Output}
\Input{$A$}
\Output{$C$}
\BlankLine
\If {condition}{
\begin{tabular}{@{\hspace{0em}}p{0.3\linewidth}p{0.4\linewidth}l}
\noalign{\vskip2pt}
$B \gets A$ & Comments & Flops \\
$C \gets B$ & Comments & Flops \\
\multicolumn{3}{@{\hspace{0em}}l}{\KwRet $C$} \\
\end{tabular}
}
\caption{Computing $C$}
\end{algorithm}
\end{document}
虽然使用表格很方便,但它的缺点是算法环境将每个表格计为一行。例如,在上图中,表格的所有三行都计为第 2 行。有没有办法修改 algorithm2e 的行计数器来计算表格行数?
答案1
根据您的示例,您可以将元素放在固定宽度的框中,并且它们应该根据需要对齐:
\documentclass{article}
\usepackage{amsmath}
\usepackage[vlined, ruled, noend]{algorithm2e}
\begin{document}
\begin{algorithm}
\LinesNumbered
\SetKwInOut{Input}{Input}
\SetKwInOut{Output}{Output}
\Input{$A$}
\Output{$C$}
\BlankLine
\If {condition}{
\begin{tabular}{@{\hspace{0em}}p{0.3\linewidth}p{0.4\linewidth}l}
\noalign{\vskip2pt}
$B \gets A$ & Comments & Flops \\
$C \gets B$ & Comments & Flops \\
\multicolumn{3}{@{\hspace{0em}}l}{\KwRet $C$} \\
\end{tabular}
}
\caption{Original: Computing $C$}
\end{algorithm}
\begin{algorithm}
\LinesNumbered
\DontPrintSemicolon
\SetKwInOut{Input}{Input}
\SetKwInOut{Output}{Output}
\Input{$A$}
\Output{$C$}
\BlankLine
\If {condition}{
\makebox[0.3\linewidth][l]{$B \gets A$}%
\makebox[0.4\linewidth][l]{Comments}%
Flops\;
\makebox[0.3\linewidth][l]{$C \gets B$}%
\makebox[0.4\linewidth][l]{Comments}%
Flops\;
\KwRet $C$\;
}
\caption{Updated: Computing $C$}
\end{algorithm}
\end{document}