Latex插入伪代码的命令

📅 2026/7/6 21:55:13 👁️ 阅读次数 📝 编程学习
Latex插入伪代码的命令

在 LaTeX 中插入代码块有多种方式,推荐使用 listings 宏包或 verbatim 环境。以下是针对 findFreshCells() 函数的具体示例:

方法一:使用 listings 宏包(推荐)

\documentclass{article}
\usepackage{listings}
\usepackage{xcolor}\lstset{basicstyle=\ttfamily\small,keywordstyle=\color{blue},commentstyle=\color{green!60!black},stringstyle=\color{red},numbers=left,numberstyle=\tiny\color{gray},breaklines=true,frame=single,language=C++  % 可根据实际语言调整
}\begin{document}\begin{lstlisting}[caption={Pseudocode of findFreshCells() function}, label=code:findFreshCells]
// 标识新生流体点:找出从固体变为流体的欧拉网格点
PetscErrorCode DecoupledIBPMSolverHyDEA::findFreshCells()
{// 20260514修改:标识阶段// ...(框架代码,需要用户根据具体应用填充逻辑)freshCellIndices.clear();return 0;
}
\end{lstlisting}\end{document}

图片

方法二:使用 verbatim 环境(简单)

\begin{verbatim}
void findFreshCells() {// 标识新生流体点for (int i = 0; i < nx; i++) {for (int j = 0; j < ny; j++) {if (isFreshFluidPoint(i, j)) {markAsFresh(i, j);}}}
}
\end{verbatim}

方法三:使用 minted 宏包(语法高亮更美观)

\documentclass{article}
\usepackage{minted}\begin{document}\begin{minted}[frame=lines,framesep=2mm,baselinestretch=1.2,bgcolor=lightgray!10,fontsize=\small,linenos
]{cpp}
void findFreshCells() {// 标识新生流体点for (int i = 0; i < nx; i++) {for (int j = 0; j < ny; j++) {if (isFreshFluidPoint(i, j)) {markAsFresh(i, j);}}}
}
\end{minted}\end{document}

快速推荐

  • 简单文档:直接用 \begin{verbatim}...\end{verbatim}
  • 正式论文/报告:使用 listings 宏包
  • 需要高质量语法高亮:使用 minted(需要安装 Pygments)

对于你周报中的 findFreshCells(),建议使用 listings 并设置语言为 C++ 或伪代码。