![如何在 algpseudocode 中将注释左对齐?](https://linux22.com/image/454693/%E5%A6%82%E4%BD%95%E5%9C%A8%20algpseudocode%20%E4%B8%AD%E5%B0%86%E6%B3%A8%E9%87%8A%E5%B7%A6%E5%AF%B9%E9%BD%90%EF%BC%9F.png)
我怎样才能让这些评论左对齐?
像这样?
\documentclass{article}
\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}
\end{document}
答案1
\documentclass{article}
\usepackage{algorithm}
\usepackage{algpseudocode}
\newlength{\commentlen}
\begin{document}
\begin{algorithm}
\caption{Euclid’s algorithm}\label{euclid}
\setlength{\commentlen}{30ex}
\begin{algorithmic}[1]
\Procedure{Euclid}{$a,b$}\Comment{\makebox[\commentlen][l]{The g.c.d. of a and b}}
\State $r\gets a\bmod b$
\While{$r\not=0$}\Comment{\makebox[\commentlen][l]{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{\makebox[\commentlen][l]{The gcd is b}}
\EndProcedure
\end{algorithmic}
\end{algorithm}
\end{document}
答案2
您可以在第一次运行时测量注释,并将最宽的注释保存在辅助文件中。在下一次运行时,注释将排版在所需宽度的框中。
\documentclass{article}
\usepackage{algorithm,algpseudocode}
\makeatletter
\newlength{\comment@width}
\renewcommand{\Comment}[1]{%
\sbox0{#1}% measure
\ifdim\wd0>\comment@width
\setlength{\comment@width}{\wd0}%
\fi
\ifcsname comment@\arabic{algorithm}@width\endcsname
\algorithmiccomment{\makebox[\csname comment@\thealgorithm @width\endcsname][l]{#1}}%
\else
\algorithmiccomment{#1}%
\fi
}
\AtBeginEnvironment{algorithmic}{\setlength{\comment@width}{0pt}}
\AtEndEnvironment{algorithmic}{%
\immediate\write\@auxout{%
\string\algcommentwidth{\thealgorithm}{\the\comment@width}%
}%
}
\newcommand{\algcommentwidth}[2]{%
\global\@namedef{comment@#1@width}{#2}%
}
\makeatother
\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}
\begin{algorithm}
\caption{Euclid’s algorithm}\label{euclid2}
\begin{algorithmic}[1]
\Procedure{Euclid}{$a,b$}\Comment{aaa bbb}
\State $r\gets a\bmod b$
\While{$r\not=0$}\Comment{ccc}
\State $a\gets b$
\State $b\gets r$
\State $r\gets a\bmod b$
\EndWhile
\State \textbf{return} $b$ \Comment{ddd}
\EndProcedure
\end{algorithmic}
\end{algorithm}
\end{document}
我利用这个事实\Comment
只是和的别名\algorithmiccomment
,所以我可以重新定义前者,并使用后者进行实际排版。