我们使用tcolorbox
如algorithm
代码所示的方式,但是算法的位置不是固定位置或者包含段落,所以我该怎么办?
\documentclass[a4paper]{article}
\usepackage[utf8]{inputenc}
\usepackage{algorithm}
\usepackage[noend]{algpseudocode}
\usepackage[skins]{tcolorbox}
\newtcolorbox{talgo}[2][]{%
blanker,float=tbp,grow to left by=#2,grow to right by=#2,
before upper={\begin{algorithm}[H]},
after upper={\end{algorithm}},
#1
}
\begin{document}
text \ref{alg:euclid}
\begin{talgo}{1cm}
\caption{Euclid's algorithm}\label{alg:euclid}
\begin{algorithmic}[1]
\Procedure{Euclid}{$m,l$}\Comment{The g.c.d. of m and l}
\State $r\gets m\bmod l$
\While{$r\not=0$}\Comment{We have the answer if r is 0}
\State $m\gets l$
\State $l\gets r$
\State $r\gets m\bmod l$
\EndWhile\label{euclidendwhile}
\State \textbf{return} $l$\Comment{The gcd is l}
\EndProcedure
\end{algorithmic}
\end{talgo}
\end{document}
答案1
float=tbp
定义中的选项优先talgo
于[H]{ option of
算法。您应该将其删除。
我借此机会改进了(在我看来)评论的布局,因此它们都从同一点开始,使用以下包eqparbox
:
\documentclass[a4paper]{article}
\usepackage[utf8]{inputenc}
\usepackage{geometry}
\usepackage{lipsum} %
\usepackage{eqparbox}
\usepackage{algorithm}
\usepackage[noend]{algpseudocode}
\usepackage[skins]{tcolorbox}
\newtcolorbox{talgo}[2][]{%
blanker, grow to left by=#2,grow to right by=#2,
before upper={\begin{algorithm}[H]},
after upper={\end{algorithm}},
#1
}
\usepackage{cleveref} %
\begin{document}
\lipsum[11]
See \cref{alg:euclid}.
\begin{talgo}{1cm}
\caption{Euclid's algorithm}\label{alg:euclid}
\begin{algorithmic}[1]
\Procedure{Euclid}{$m,l$}\Comment{\eqmakebox[Com][l]{The g.c.d. of m and l}}
\State $r\gets m\bmod l$
\While{$r\not=0$}\Comment{\eqmakebox[Com][l]{We have the answer if r is 0}}
\State $m\gets l$
\State $l\gets r$
\State $r\gets m\bmod l$
\EndWhile\label{euclidendwhile}
\State \textbf{return} $l$\Comment{\eqmakebox[Com][l]{The gcd is l}}
\EndProcedure
\end{algorithmic}
\end{talgo}
\end{document}