算法包中的缩进 If 语句

算法包中的缩进 If 语句

我有以下代码,我正在尝试将 IF 语句缩进到语句 5 的正下方。如果您能帮助我解决这个问题,我将不胜感激。谢谢。

\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{algorithm,algorithmic}

\begin{document}

\begin{algorithm}[t]
{               
\begin{algorithmic}[1]
\STATE {Input}: statement 1
\STATE statement 2
\FOR {statement 3}
\STATE statement 4
\STATE \hspace{.5cm} statement 5
\IF{statement 6}
\STATE statement 7
\ELSE
\STATE statement 9
\ENDIF
\STATE statement 10
\ENDFOR         
\end{algorithmic}
\caption{title}
}                       
\end{algorithm} 

\end{document}

答案1

在以下示例中,定义了一对新命令\SCOPE和。和之间的内容将具有额外的缩进级别。\ENDSCOPE\SCOPE\ENDSCOPE

\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{algorithm,algorithmic}
\usepackage{xpatch}

\makeatletter
% defined only inside "algorithmic" environment
\xpatchcmd\algorithmic
  {\newcommand{\IF}}
  {%
    \newcommand\SCOPE{\begin{ALC@g}}%
    \newcommand\ENDSCOPE{\end{ALC@g}}%
    \newcommand{\IF}%
  }
  {}{\fail}
\makeatother

\begin{document}

\begin{algorithm}[t]  
  \begin{algorithmic}[1]
    \STATE {Input}: statement 1
    \STATE statement 2
    \FOR {statement 3}
      \STATE statement 4
      \SCOPE    % <<< new command
        \STATE statement 5
        \IF{statement 6}
          \STATE statement 7
        \ELSE
          \STATE statement 9
        \ENDIF
      \ENDSCOPE % <<< new command
      \STATE statement 10
    \ENDFOR
  \end{algorithmic}
  \caption{title}
\end{algorithm}

\end{document}

在此处输入图片描述

相关内容