![顶部带标题的框式算法](https://linux22.com/image/363045/%E9%A1%B6%E9%83%A8%E5%B8%A6%E6%A0%87%E9%A2%98%E7%9A%84%E6%A1%86%E5%BC%8F%E7%AE%97%E6%B3%95.png)
我希望获得一个带标题的盒装算法。我还需要控制标题格式和标题。
我尝试使用算法包裹:
%algorithms
\usepackage[boxed]{algorithm}
\usepackage{algorithmicx,algpseudocode}
% Change float style of algorithm from "ruled" to "plaintop"
\floatstyle{plaintop}
\restylefloat{algorithm}
% Change caption format
\captionsetup[algorithm]{font=scriptsize,labelformat=bf-gara,justification=raggedright,singlelinecheck=false,name=Algorithm}
% Change caption heading
\renewcommand{\thealgorithm}{A.\arabic{algorithm}}
但是,它不会在算法周围画出方框。我可以要求所有浮点数都被框起来,但这也会影响图形和表格,我不希望它们被框起来。
或者,我可以使用algorithm2e
包,它提供对标题位置的更多控制,但是当我需要指定标题格式和标题时就会遇到麻烦:
\thealgorithm undefined. \renewcommand{\thealgorithm}
Argument of \ALG@cmd@2@algorithmiccomment has an extra }. \While{$r\not=0$}\Comment{
我怎样才能同时节省两种方式?谢谢!
答案1
在旧boxed
样式的基础上自己写一种新样式:
\documentclass{article}
\usepackage{algorithm,algpseudocode,caption}
% Define a new boxedtopcap float style
\makeatletter
\newcommand\fs@boxedtopcap{\def\@fs@cfont{\bfseries}\let\@fs@capt\floatc@plain
\def\@fs@pre{\setbox\@currbox\vbox{\hbadness10000
\moveleft3.4pt\vbox{\advance\hsize by6.8pt
\hrule \hbox to\hsize{\vrule\kern3pt
\vbox{\kern3pt\box\@currbox\kern3pt}\kern3pt\vrule}\hrule}}}%
\def\@fs@mid{\kern2pt}%
\def\@fs@post{}\let\@fs@iftopcapt\iftrue}
\makeatother
% Change float style of algorithm from "ruled" to "plaintop"
\floatstyle{boxedtopcap}
\restylefloat{algorithm}
% Change caption format
\captionsetup[algorithm]{
justification = raggedright,
singlelinecheck = false,
name = Algorithm
}
% Change caption heading
\renewcommand{\thealgorithm}{A.\arabic{algorithm}}
\begin{document}
\begin{algorithm}
\caption{Euclid's algorithm}
\begin{algorithmic}[1]
\Procedure{Euclid}{$a,b$}\Comment{The g.c.d.\ of $a$ and $b$}
\State $r \gets a \bmod b$
\While{$r \neq 0$}\Comment{We have the answer if $r$ is $0$}
\State $a \gets b$
\State $b \gets r$
\State $r \gets a \bmod b$
\EndWhile
\State \textbf{return} $b$\Comment{The g.c.d.\ is $b$}
\EndProcedure
\end{algorithmic}
\end{algorithm}
\end{document}