在垂直线中对齐算法中的等号

在垂直线中对齐算法中的等号

[1]中描述的代码产生以下输出:

算法 Tex 输出

为了描述我的算法,我需要等号在一条垂直线上完美对齐,但目前仍然有一个小但明显的偏移。


[1] TeX 代码:

\usepackage{algorithmicx}
\usepackage{algorithm}

\newcommand{\algrhs}[1]{\hfill \parbox[t]{\algrhswidth}{#1}}

\begin{algorithm} [H]
\begin{algorithmic}[1] 
    \State $A_1 = B_1 + C_1 $ \algrhs{$ A_2 = B_2 - C_2$}
    \State $X_1 = Y_1 + Z_1$ \algrhs{$ X_2 = Y_2 + Z_2$}
\end{algorithmic}
\end{algorithm}

答案1

您需要确保等式两边宽度相等。可以通过将较小的元素放置在宽度较大的框内\makeboxX_x宽于A_xB_x +/- C_x宽于Y_x +/- Z_x)来实现:

在此处输入图片描述

\documentclass{article}
\usepackage{algpseudocode}
\usepackage{algorithm,calc}

\newcommand{\mathbox}[3][r]{\makebox[\widthof{$#2$}][#1]{$#3$}}

\begin{document}

\begin{algorithm}[H]
  \begin{algorithmic}[1] 
    \State $\mathbox{X_1}{A_1} = B_1 + C_1$ \hfill $\mathbox{X_2}{A_2} = B_2 - C_2$
    \State $X_1 = \mathbox[l]{B_1 + C_1}{Y_1 + Z_1}$ \hfill
      $X_2 = \mathbox[l]{B_2 - C_2}{Y_2 + Z_2}$
  \end{algorithmic}
\end{algorithm}

\end{document}

在上面的例子中,我做了如下\mathbox行为\makebox[<width>][<alignment>]{<stuff>}calc用于通过 测量某物的宽度\widthof

答案2

使用\eqmakebox[<tag>][<pos>]{<text>}将所有内容设置在相同宽度框内的相同<text>位置下。<pos><tag>

\documentclass{article}
\usepackage{algpseudocode}
\usepackage{algorithm,eqparbox}

\begin{document}

\begin{algorithm}[H]
  \begin{algorithmic}[1] 
    \State $\eqmakebox[lhs1][r]{$A_1$} = B_1 + C_1$ \hfill
      $\eqmakebox[lhs2][r]{$A_2$} = \eqmakebox[rhs2][l]{$B_2 - C_2$}$
    \State $\eqmakebox[lhs1][r]{$X_1$} = Y_1 + Z_1$ \hfill 
      $\eqmakebox[lhs2][r]{$X_2$} = \eqmakebox[rhs2][l]{$Y_2 + Z_2$}$
  \end{algorithmic}
\end{algorithm}

\end{document}

相关内容