• 最前面加入listings包:

    \usepackage{listings}
    
  • 在代码段中添加代码

    \begin{lstlisting}
    % 代码段
    \end{lstlisting}
    
  • 格式调整

    \lstset{
     columns=fixed,       
     numbers=left,                                        % 在左侧显示行号
     numberstyle=\tiny\color{gray},                       % 设定行号格式
     frame=none,                                          % 不显示背景边框
     backgroundcolor=\color[RGB]{245,245,244},            % 设定背景颜色
     keywordstyle=\color[RGB]{40,40,255},                 % 设定关键字颜色
     numberstyle=\footnotesize\color{darkgray},           
     commentstyle=\it\color[RGB]{0,96,96},                % 设置代码注释的格式
     stringstyle=\rmfamily\slshape\color[RGB]{128,0,0},   % 设置字符串格式
     showstringspaces=false,                              % 不显示字符串中的空格
     language=c++,                                        % 设置语言
    }
    
  • 样例

    \lstset{
     columns=fixed,       
     numbers=left,                                        % 在左侧显示行号
     numberstyle=\tiny\color{gray},                       % 设定行号格式
     frame=none,                                          % 不显示背景边框
     backgroundcolor=\color[RGB]{245,245,244},            % 设定背景颜色
     keywordstyle=\color[RGB]{40,40,255},                 % 设定关键字颜色
     numberstyle=\footnotesize\color{darkgray},           
     commentstyle=\it\color[RGB]{0,96,96},                % 设置代码注释的格式
     stringstyle=\rmfamily\slshape\color[RGB]{128,0,0},   % 设置字符串格式
     showstringspaces=false,                              % 不显示字符串中的空格
     language=c++,                                        % 设置语言
    }
    \begin{lstlisting}
    
    #include <iostream>
    using namespace std;
    
    int main()
    {
        cout<<"hello"<<endl;
        return 0;
    }
    \end{lstlisting}
    
    
    \end{document}
    
  • 效果
    在这里插入图片描述

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐