Algorithm2e에서 방정식을 사용할 때 생성되는 추가 선

Algorithm2e에서 방정식을 사용할 때 생성되는 추가 선

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그러한 예에는 사용하지 마십시오 .

관련 정보