我怎样才能让这些评论左对齐?
像这样?
\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
,所以我可以重新定义前者,并使用后者进行实际排版。