LaTeX 中 algorithm 环境完整指南
在科研论文里,写清楚算法步骤通常需要用到 伪代码环境。最常见的选择有两个包:
algorithm2e—— 功能最强大,适合期刊/学位论文algorithmicx+algpseudocode—— 更灵活、可定制,常用于会议模板
1️⃣ 常用包的选择
ruled:算法标题在上方,并有横线vlined:每行后加竖线(折线效果),用来表示语句块作用域linesnumbered:为每一行添加行号- 提供
\KwIn,\KwOut,\For,\If,\While等高阶命令 - 自带行号、自动缩进、美观
algorithm负责浮动体,类似 figure/tablealgpseudocode提供命令,比如\State,\If,\For- 优点:高度可控,适合需要精细排版的场景
algorithmicx + algpseudocode
\usepackage{algorithm} \usepackage{algpseudocode}
algorithm2e
\usepackage[ruled,vlined]{algorithm2e}
2️⃣ 基本结构
algorithm2e 示例
\begin{algorithm}[!t]
\SetAlgoLined
\caption{Power Allocation Algorithm}
\KwIn{User set $\mathcal{U}$, channel gains $h_u$, total power $P$}
\KwOut{Optimal power allocation {$p_u$}}
Initialize $p_u \gets 0$ for all u\;
\For{each user $u \in \mathcal{U}$}{
Compute priority weight $w_u$\;
\If{$w_u > \text{threshold}$}{
Allocate power $p_u \gets f(h_u, w_u)$\;
}
}
\Return {$p_u$}
\end{algorithm}
algorithmicx + algpseudocode 示例
\begin{algorithm}[!t]
\caption{Power Allocation Algorithm}
\begin{algorithmic}[1]
\Require User set $\mathcal{U}$, channel gains $h_u$, total power $P$
\Ensure Optimal power allocation {$p_u$}
\State Initialize $p_u \gets 0$ for all u
\For{each user $u \in \mathcal{U}$}
\State Compute priority weight $w_u$
\If{$w_u > \text{threshold}$}
\State Allocate power $p_u \gets f(h_u, w_u)$
\EndIf
\EndFor
\State \Return {$p_u$}
\end{algorithmic}
\end{algorithm}
3️⃣ 注意事项
🔹 (1) 包冲突问题
- 有些模板(如 IEEEtran)自带 环境,可能会和 冲突


