如何在算法环境中使用对齐环境或制表符?

如何在算法环境中使用对齐环境或制表符?

我希望这些表达式对齐,以便字距调整和略有不同的字符宽度不会导致整体外观不均匀。我尝试使用环境,alignalgorithm结果却出现了错误。以下是 MWE:

\documentclass[a4paper]{article}

\usepackage[english]{babel}
\usepackage[utf8]{inputenc}
\usepackage{algorithm}
\usepackage[noend]{algpseudocode}

\begin{document}

\begin{algorithm}
\caption{Euclid’s algorithm}\label{alg:euclid}
\begin{algorithmic}[1]
\Procedure{Euclid}{$m,l$}\Comment{The g.c.d. of m and l}
\State $r\gets m\bmod l$
\While{$r\not=0$}\Comment{We have the answer if r is 0}
\State $m\gets l$
\State $l\gets r$
\State $r\gets m\bmod l$
\EndWhile\label{euclidendwhile}
\State \textbf{return} $l$\Comment{The gcd is l}
\EndProcedure
\end{algorithmic}
\end{algorithm}

\end{document}

来源:https://www.writelatex.com/examples/euclids-algorithm-an-example-of-how-to-write-algorithms-in-latex/mbysznrmktqf

答案1

这在本质上非常类似于约翰的回答, 使用mathtools的数学重叠工具:

在此处输入图片描述

\documentclass{article}

\usepackage{mathtools,algorithm}
\usepackage[noend]{algpseudocode}

\begin{document}

\begin{algorithm}
  \caption{Euclid's algorithm}
  \begin{algorithmic}[1]
    \Procedure{Euclid}{$m,l$}\Comment{The g.c.d.\ of~$m$ and~$l$}
      \State $r\gets m\bmod l$
      \While{$r \neq 0$}\Comment{We have the answer if~$r$ is $0$}
        \State $m \gets l$
        \State $\hphantom{m}\mathllap{l} \gets r$
        \State $\hphantom{m}\mathllap{r} \gets m\bmod l$
      \EndWhile
      \While{$r \neq 0$}\Comment{We have the answer if~$r$ is $0$}
        \State $m \gets l$
        \State $\mathrlap{l}\hphantom{m} \gets r$
        \State $\mathrlap{r}\hphantom{m} \gets m\bmod l$
      \EndWhile
      \State \textbf{return} $l$\Comment{The g.c.d.\ is~$l$}
    \EndProcedure
  \end{algorithmic}
\end{algorithm}

\end{document}

\phantom通过适当放置s 并伴随 over ping,可以轻松实现左对齐或右对齐lap\mathllap= left over lap; \mathrlap= right over lap

答案2

如果您确实想这样做,您可以将\makebox其设置为恒定宽度。

对齐算法

\documentclass[a4paper]{article}

\usepackage[english]{babel}
\usepackage[utf8]{inputenc}
\usepackage{algorithm}
\usepackage[noend]{algpseudocode}

\newlength{\maxwidth}
\newcommand{\algalign}[2]% #1 = text to left, #2 = text to right
{\makebox[\maxwidth][r]{$#1{}$}${}#2$}

\begin{document}

\begin{algorithm}
\caption{Euclid’s algorithm}\label{alg:euclid}
\begin{algorithmic}[1]
\Procedure{Euclid}{$m,l$}\Comment{The g.c.d. of m and l}
\State $r\gets m\bmod l$
\While{$r\not=0$}\Comment{We have the answer if r is 0}
\settowidth{\maxwidth}{$m$}% use the widest one
\State \algalign{m}{\gets l}
\State \algalign{l}{\gets r}
\State \algalign{r}{\gets m\bmod l}
\EndWhile\label{euclidendwhile}
\State \textbf{return} $l$\Comment{The gcd is l}
\EndProcedure
\end{algorithmic}
\end{algorithm}

\end{document}

相关内容