在算法环境中从新行开始写注释

在算法环境中从新行开始写注释

我正在写伪代码/算法。写注释时,它们会右对齐。这真的很不方便,因为我的一些注释很长,需要多行。此外,区分代码和注释也有点困难。

我的算法很长,需要多页;因此,我不得不将其分成多个块。

以下是一个例子:

\usepackage{algorithm,algpseudocode}
\usepackage{caption}

\algrenewcommand\algorithmicrequire{\textbf{Input:}}
\algrenewcommand\algorithmicensure{\textbf{Output:}}

\begin{algorithm}
\caption{$y = f(x)$}
\label{my_algorithm}

\begin{algorithmic}[1]
\Require \strut $x_0$
\Ensure $y$
\State $x \gets x_0$
\State $y \gets x^2$ \Comment{This is a very long comment and it would be nice if it would have its own line. It could also be written in a different colour.}
\State  $x_1 \gets y$
\algstore{myalg}
\end{algorithmic}
\end{algorithm}

There is a page break between different blocks of code, but the algorithm continues:

\begin{algorithm}
\addtocounter{algorithm}{-1}
\begin{algorithmic}[1]
\algrestore{myalg}
\State\strut  $x \gets x_1$ \Comment{We continue here from where we left. It would be convenient to have the comment in its own line before the variable declaration.}
\State $y = x^2$
\end{algorithmic}
\end{algorithm}

现在代码如下所示: 在此处输入图片描述

我怎样才能使注释有自己的行,并且可能与代码有不同的颜色?

答案1

\documentclass{article}
\usepackage{algorithm}
\usepackage[beginLComment=/*~,endLComment=~*/]{algpseudocodex}
\algrenewcommand{\algorithmicrequire}{\textbf{Input:}}
\algrenewcommand{\algorithmicensure}{\textbf{Output:}}
\begin{document}
\begin{algorithm}
\caption{$y = f(x)$}
\label{my_algorithm}
\begin{algorithmic}[1]
\Require \strut $x_0$
\Ensure $y$
\State $x \gets x_0$
\State $y \gets x^2$ \LComment{\color{red} This is a very long comment and it would be nice if it would have its own line. It could also be written in a different colour.}
\State  $x_1 \gets y$
\algstore{myalg}
\end{algorithmic}
\end{algorithm}
There is a page break between different blocks of code, but the algorithm continues:
\begin{algorithm}
\addtocounter{algorithm}{-1}
\begin{algorithmic}[1]
\algrestore{myalg}
\State\strut  $x \gets x_1$ \LComment{We continue here from where we left. It would be convenient to have the comment in its own line before the variable declaration.}
\State $y = x^2$
\end{algorithmic}
\end{algorithm}
\end{document}

在此处输入图片描述

相关内容