如何在 LaTeX 文档中添加 1 行源代码(源代码片段)?

如何在 LaTeX 文档中添加 1 行源代码(源代码片段)?

解释这一点的最简单的方法可能是提供一个我想要做的事情的例子:

考虑 LaTeX 文档的以下部分。

Calls to the function
// a blank line
get_next_random_number(int) // This should be monospace (texttt) and centered on page
// another blank line
should be independent of previous calls, resulting in a Fourier Space distribution with no eigenfrequency.

到目前为止我有这个(LaTeX 代码):

Calls to \\\\\texttt{get_next_random_number(int)}\\\\should be independent of previous calls, resulting in a Fourier Space distribution with no eigenfrequency.

但我不知道如何设置它,使其位于屏幕中央而不是左对齐。

答案1

你在寻找类似这样的东西吗?

在此处输入图片描述

编辑: 文档类,如articlereportbool许多其他类,都包含用于编写逐字文本的功能,即用打字机编写的文本。它有两种形式:

\begin{verbatim}
       text_which_will_appear_in_final_document_as_here
       (with "_" between words, which otherwise require
        to be written as "\_" ... 
\end{verbatim}

人们通常使用它来呈现一些代码(就像你的情况一样)或以简短形式在文本中通过\verb{...}\verb+...+或任何其他相等字符对来呈现此代码。上图是我使用以下 MWE 获得的:

\documentclass[12pt]{article}

    \begin{document}
Calls to
    \begin{center}
\verb+get_next_random_number(int)+
    \end{center}
should be independent of previous calls, resulting in a Fourier Space distribution with no eigenfrequency.
    \end{document} 

我选择这种形式,因为你问如何用打字机字符在文本中居中书写代码。例如,如果你想要让此代码(例如四个字符)形成左文本边框,你可以这样写

Calls to
\begin{verbatim}
    get_next_random_number(int)
\end{verbatim}
should be independent of previous calls, resulting in a Fourier Space distribution with no eigenfrequency.

对于逐字记录环境,还存在诸如fancyvrb和其他专门的包,这使得能够更复杂地编写逐字记录文本。

答案2

另一个选择是使用fancyvrb包和BVerbatim环境:

\documentclass{article}
\usepackage{fancyvrb}
\begin{document
Calls to the function
\begin{center}
\begin{BVerbatim}
get_next_random_number(int)
\end{BVerbatim}
\end{center}
should be independent of previous calls, resulting in a Fourier Space distribution with no eigenfrequency.
\end{document}

答案3

怎么样:

Calls to 

\begin{center}\texttt{get_next_random_number(int)}\end{center}

should be independent of previous calls, resulting in a Fourier Space distribution with no eigenfrequency.

相关内容