添加宏
\usepackage{algorithm2e}
也可以设置一些参数:
\usepackage[ruled,linesnumbered]{algorithm2e}
ruled
在顶部和底部画一条线,标题左对齐;
linesnumbered
:显示行号
将 “Algorithm” 替换成 “算法”
使用命令SetAlgorithmName
% SetAlgorithmName{algorithmnam}{algorithmautorefname}{list of algorithms name}
\SetAlgorithmName{算法}{算法}{算法}
算法注释
% /*注释*/
\tcc{注释}
% //注释
\tcp{注释}
自定义注释
设置注释被/* */
包围
\SetKwComment{Comment}{/* }{ */}
注释
\Comment*[r]{This is a comment}
高亮某一行代码
局部修改文字颜色的方式,可以修改普通代码行的颜色,需要用到的宏包:
\usepackage{color}
{\color{<颜色名>}<原始代码内容>}
实例:
\begin{algorithm}[H]
\caption{Put your caption here}
\SetKwInput{KwInput}{Input} % Set the Input
\SetKwInput{KwOutput}{Output} % set the Output
\DontPrintSemicolon
\KwInput{Your Input}
\KwOutput{Your output}
\KwData{Testing set $x$}
% Set Function Names
\SetKwFunction{FMain}{Main}
\SetKwFunction{FSum}{Sum}
\SetKwFunction{FSub}{Sub}
% Write Function with word ``Function''
\SetKwProg{Fn}{Function}{:}{}
\Fn{\FSum{$first$, $second$}}{
a = first\;
b = second\;
{\color{red}sum = first + second\;}
\KwRet sum\;
}
\;
% Write Function with word ``Def''
\SetKwProg{Fn}{Def}{:}{}
\Fn{\FSub{$first$, $second$}}{
a = first\;
b = second\;
sum = first - second\;
\KwRet sum\;
}
\;
\SetKwProg{Fn}{Function}{:}{\KwRet}
\Fn{\FMain}{
a = 5\;
b = 10\;
Sum(5, 10)\;
Sub(5, 10)\;
print Sum, Sub\;
\KwRet 0\;
}
\end{algorithm}
实现效果: