如何在算法环境中更改特定注释的缩进?

如何在算法环境中更改特定注释的缩进?

我有以下代码:

\documentclass{article}  

\usepackage{algorithm}
\usepackage{algorithmic}

\newcounter{ALC@tempcntr}% Temporary counter for storage
\newcommand{\LCOMMENT}[1]{%
    \setcounter{ALC@tempcntr}{\arabic{ALC@rem}}% Store old counter
    \setcounter{ALC@rem}{1}% To avoid printing line number
    \item //#1 % Display comment + does not increment list item counter
    \setcounter{ALC@rem}{\arabic{ALC@tempcntr}}% Restore old counter
}%

\begin{document} 
        
    \begin{algorithm}[!t]
        \caption{A sample algorithm.}
        \textbf{Input:}  Some input.\\
        \textbf{Output:} Some output.
        
        \begin{algorithmic}[1]
            \LCOMMENT {1st Step:}
            \STATE Do something.
            \LCOMMENT {2nd Step:} 
            \IF {$A \geq B$}
            \STATE Do something.
            \LCOMMENT {3rd Step:}
            \ELSE 
            \STATE Do something.            
            \ENDIF
        \end{algorithmic}
    \end{algorithm}

\end{document}

产生以下算法。请注意,我使用新的注释命令(即 \LCOMMENT)来使注释以 // 开头,更重要的是,不使用行号来注释。但是,在上述情况下,我希望第 3 条注释具有与算法中的下一行(即第 4 行)相同的缩进,而不是与第 3 行相同的缩进。有没有简单的方法可以做到这一点? 在此处输入图片描述

答案1

第一级之后的每一级algorithmic都会增加\algorithmicindent当前缩进。可以通过查看 来访问该级别\@listdepth,因此我们需要添加 倍的负\@listdepth-1空间\algorithmicindent

\documentclass{article}  

\usepackage{algorithm}
\usepackage{algorithmic}

\newcounter{ALC@tempcntr}% Temporary counter for storage
\newcommand{\LCOMMENT}[1]{%
    \setcounter{ALC@tempcntr}{\arabic{ALC@rem}}% Store old counter
    \setcounter{ALC@rem}{1}% To avoid printing line number
    \item \removemargin // #1 % Display comment + does not increment list item counter
    \setcounter{ALC@rem}{\arabic{ALC@tempcntr}}% Restore old counter
}
\makeatletter
\newcommand{\removemargin}{\hspace*{\numexpr1-\@listdepth\relax\algorithmicindent}}
\makeatother

\begin{document} 
        
    \begin{algorithm}[!t]
        \caption{A sample algorithm.}
        \textbf{Input:}  Some input.\\
        \textbf{Output:} Some output.
        
        \begin{algorithmic}[1]
            \LCOMMENT {1st Step:}
            \STATE Do something.
            \LCOMMENT {2nd Step:} 
            \IF {$A \geq B$}
            \STATE Do something.
            \LCOMMENT {3rd Step:}
\IF{x}\STATE a \LCOMMENT {what?}\ELSE \STATE b \ENDIF % to show further indentation
            \ELSE 
            \STATE Do something.            
            \ENDIF
        \end{algorithmic}
    \end{algorithm}

\end{document}

在此处输入图片描述

相关内容