在演算法2e中使用方程式時所建立的附加線

在演算法2e中使用方程式時所建立的附加線

考慮以下範例,將equation*s 放置在algorithm環境中:

\documentclass{standalone}

\usepackage{amsmath}
\usepackage{algorithm2e}

\LinesNumbered

\begin{document}
\begin{algorithm}[H]
  \SetAlgoLined
  \KwData{this text}
  \KwResult{how to write algorithm with \LaTeX2e }
  \ForEach{first loop} {
    \begin{equation*}
      a^2 + b^2 = c^2
    \end{equation*}
    After \;
    After \;
    After \;
  }
  \ForEach{second loop} {
    Before
    \begin{equation*}
      a^2 + b^2 = c^2
    \end{equation*}
    After \;
    After \;
    After \;
  }
  \caption{How to write algorithms}
\end{algorithm}
\end{document}

這會產生以下輸出:

輸出

問題在於方程式的間距。具體來說,在第 2 行中,我們看到添加了大量垂直空間,而實際上不需要。事實上,第 7 行表明可以在方程式開始之前在佈局中留下的空白區域內添加一些文字。更重要的是,行號 2 位於方程式上方,而不是與之對齊。

有沒有辦法讓方程式表現得更自然並避免引入額外的空間?

答案1

快速破解:

\documentclass{standalone}

\usepackage{amsmath}
\usepackage{algorithm2e}

\LinesNumbered

\begin{document}
\begin{algorithm}[H]
  \SetAlgoLined
  \KwData{this text}
  \KwResult{how to write algorithm with \LaTeX2e }
  \ForEach{first loop} {
    \parbox{\hsize}{%
      \[
      a^2 + b^2 = c^2
      \]
    }\par
    After \;
    After \;
    After \;
  }
  \ForEach{second loop} {
    Before\par
    \parbox{\hsize}{%
      \[
      a^2 + b^2 = c^2
      \]
    }\par
    After \;
    After \;
    After \;
  }
  \caption{How to write algorithms}
\end{algorithm}
\end{document}

在此輸入影像描述

答案2

我會定義一個特定的環境。

\documentclass{article}

\usepackage{amsmath}
\usepackage{algorithm2e}

\NewDocumentEnvironment{algoequation}{b}{%
  \par\makebox[\dimeval{\hsize}]{$\displaystyle#1$}\par
}{}


\LinesNumbered

\begin{document}
\begin{algorithm}[H]
  \SetAlgoLined
  \KwData{this text}
  \KwResult{how to write algorithm with \LaTeX2e }
  \ForEach{first loop} {
    \begin{algoequation}
      a^2 + b^2 = c^2
    \end{algoequation}
    After \;
    After \;
    After \;
  }
  \ForEach{second loop} {
    Before
    \begin{algoequation}
      a^2 + b^2 = c^2
    \end{algoequation}
    After \;
    After \;
    After \;
  }

\caption{How to write algorithms}
\end{algorithm}

\end{document}

在此輸入影像描述

透過簡單的更改,您可以獲得固定縮排:

\NewDocumentEnvironment{algoequation}{b}{%
  \par\hspace*{\algomargin}$\displaystyle#1$\par
}{}

在此輸入影像描述

這就是建議定義特定環境的原因:您不受特定表示的束縛,並且可以輕鬆修改定義,但不能修改文件程式碼。

邊注。請不要使用standalone此類範例。

相關內容