\documentclass[11pt,a4paper] {article}
%\usepackage{fontspec}
\usepackage{listings}
\usepackage{xcolor}
%\setmainfont[BoldFont=黑体]{宋体}
%\XeTeXlinebreaklocale "zh"
%\XeTeXlinebreakskip = 0pt plus 1pt minus 0.1pt
%\linespread{1.5}
\lstset{
numbers = left,
framexleftmargin=10mm,
frame=none,
backgroundcolor=\color[rgb]{245,245,244},
keywordstyle=\bf\color{blue},
identifierstyle=\bf,
numberstyle=\color[RGB]{0,192,192},
commentstyle=\it\color[RGB]{0,96,96},
stringstyle=\rmfamily\s1shape\color[RGB]{128,0,0},
showstringspaces=true
}
\begin {document}
\title{实验课}
\author{ coolwind}
\maketitle
\paragraph{}
你好,世界!
\begin{lstlisting}[language=C]
#include <stdio.h>
int main()
{
printf("Hello world!\n");
for (int i = 0; i < 100; i ++)
{
for (int j = 0; j < 100; j ++)
{
int tmp = i + j;
}
}
return 0;
}
\end{lstlisting}
\end {document}
答案1
部分5.6 自动格式化软件包listings
文档描述了如何获得自动缩进。这个想法是使用\lstdefineformat
(listings
必须加载选项formats
)定义格式:
\documentclass[11pt,a4paper] {article}
\usepackage[formats]{listings}
\usepackage{xcolor}
\lstdefineformat{C}{%
\{=\newline\string\newline\indent,%
\}=[;]\newline\noindent\string\newline,%
\};=\newline\noindent\string\newline,%
;=[\ ]\string\space}
\lstset{
numbers = left,
framexleftmargin=10mm,
frame=none,
backgroundcolor=\color[RGB]{245,245,244},
keywordstyle=\bfseries\color{blue},
identifierstyle=\bfseries,
numberstyle=\color[RGB]{0,192,192},
commentstyle=\it\color[RGB]{0,96,96},
stringstyle=\rmfamily\slshape\color[RGB]{128,0,0},
showstringspaces=true
}
\begin {document}
\begin{lstlisting}[language=C,format=C]
#include <stdio.h>
int main()
{
printf("Hello world!\n");
for (int i = 0; i < 100; i ++)
{
for (int j = 0; j < 100; j ++)
{
int tmp = i + j;
}
}
return 0;
}
\end{lstlisting}
\end{document}
如果原始代码对于讨论的问题不重要,我会删除一些行;我还修复了颜色规范中的错误(从 更改rgb
为RGB
)