latex 代码框

\usepackage{listings}
\usepackage{xcolor} 


\definecolor{mygreen}{rgb}{0,0.6,0}
\definecolor{mygray}{rgb}{0.5,0.5,0.5}
\definecolor{mymauve}{rgb}{0.58,0,0.82}
\lstset{ %
backgroundcolor=\color{white},   % choose the background color
basicstyle=\footnotesize\ttfamily,        % size of fonts used for the code
columns=fullflexible,
breaklines=true,                 % automatic line breaking only at whitespace
captionpos=b,                    % sets the caption-position to bottom
tabsize=4,
commentstyle=\color{mygreen},    % comment style
escapeinside={\%*}{*)},          % if you want to add LaTeX within your code
keywordstyle=\color{blue},       % keyword style
stringstyle=\color{mymauve}\ttfamily,     % string literal style
frame=shadowbox,
rulesepcolor=\color{red!20!green!20!blue!20},
% identifierstyle=\color{red},
numbers=left, 
numberstyle=\tiny,
% escapeinside=' ',
xleftmargin=2em,
xrightmargin=2em, 
aboveskip=1em
}

\begin{document}
\maketitle
\pagestyle{plain}

\begin{lstlisting} [language=c++]
int main(int argc, char ** argv) 
{ 

    printf("Hello world! \n"); 

    return 0; 
} 
\end{lstlisting}
\end{document}

在这里插入图片描述

### 在 LaTeX 中进行代码排版 为了在 LaTeX 文档中实现良好的代码排版效果,通常会使用 `listings` 或者 `minted` 这样的包来处理源代码展示。下面介绍基于 `listings` 的方法。 #### 使用 listings 包设置全局样式 通过 `\lstset` 命令可以在文档的导言区配置适用于整个文档中的代码片段样式的公共参数[^2]: ```tex \documentclass{article} \usepackage{xcolor} \usepackage{listings} % 设置代码风格 \lstset{ language=Python, basicstyle=\ttfamily\footnotesize, % 字体大小与类型 keywordstyle=\bfseries\color{blue}, % 关键字颜色 commentstyle=\itshape\color{gray}, % 注释的颜色 stringstyle=\color{red}, % 字符串颜色 showstringspaces=false % 不显示字符串内的空格标记 } ``` 此段落展示了如何利用 `basicstyle`, `keywordstyle`, `commentstyle`, 和 `stringstyle` 来定制化代码外观,并关闭了不必要的空白字符高亮功能。 #### 定义特定编程语言环境下的局部属性 除了上述全局设定外,还可以针对不同类型的代码块单独指定额外选项。例如,在插入 Python 脚本时增加行号并控制缩进级别: ```tex \begin{lstlisting}[language=Python,caption={示例程序}] def hello_world(): print("Hello world!") hello_world() \end{lstlisting} ``` 这里设置了 `caption` 参数用于给定代码框加上描述性的标题;同时指定了具体的编程语言以便更精确地解析语法特性。 对于其他语言的支持也十分简单,只需更改 `language` 属性即可适应多种不同的开发需求。 #### 处理多栏布局中的浮动对象定位问题 当遇到跨两栏的文章结构时,应该特别留意图片或大型代码列表的位置安排。为了避免这些元素意外移动至文章结尾处,建议预先规划好它们的确切安放地点,并适当调整周围正文内容以预留足够的空间[^1]。 另外值得注意的是,某些特殊情况下可能还需要手动干预浮动物件的行为模式,比如强制其停留在当前位置而不是随文本流自由漂移。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

颹蕭蕭

白嫖?

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值