我是 Latex 新手。我想保留算法块中的字体类型,但只将诸如for
和之类的关键字设置if
为粗体。我不确定ttdefault
在算法块内设置是否是最佳方法。任何帮助都将不胜感激。
\documentclass{article}
\usepackage[ruled]{algorithm}
\usepackage[]{algorithmicx}
\usepackage[noend]{algpseudocode}
% make keywords below bold instead
\newcommand\keywordfont{\ttfamily\bfseries}
\algrenewcommand\algorithmicend{{\keywordfont end}}
\algrenewcommand\algorithmicdo{{\keywordfont do}}
\algrenewcommand\algorithmicwhile{{\keywordfont while}}
\algrenewcommand\algorithmicfor{{\keywordfont for}}
\algrenewcommand\algorithmicforall{{\keywordfont for all}}
\algrenewcommand\algorithmicloop{{\keywordfont loop}}
\algrenewcommand\algorithmicrepeat{{\keywordfont repeat}}
\algrenewcommand\algorithmicuntil{{\keywordfont until}}
\algrenewcommand\algorithmicprocedure{{\keywordfont procedure}}
\algrenewcommand\algorithmicfunction{{\keywordfont function}}
\algrenewcommand\algorithmicif{{\keywordfont if}}
\algrenewcommand\algorithmicthen{{\keywordfont then}}
\algrenewcommand\algorithmicelse{{\keywordfont else}}
\algrenewcommand\algorithmicrequire{{\keywordfont Require:}}
\algrenewcommand\algorithmicensure{{\keywordfont Ensure:}}
\algrenewcommand\algorithmicreturn{{\keywordfont return}}
\begin{document}
\begin{algorithm}[H]
% this may not be the best approach
\renewcommand{\ttdefault}{cmtt}
\keywordfont{\ttfamily}
\begin{algorithmic}
\caption{Gaussian sampler using Taylor series}
\State sigma $\gets 8 / \sqrt{2 \pi}$
\State variance $\gets$ sigma$^2$
\State \Comment{returns pdf(x) = standard Gaussian pdf}
\Function{pdf}{x}
\Return $e^{(-x^2 / 2)} / \sqrt{2 \pi}$
\EndFunction
\State \Comment{returns CDF(z) = standard Gaussian CDF using Taylor approximation}
\Function{cdf}{x}
\If{x $<$ -variance}
\Return 0.0
\ElsIf{x $>$ variance}
\Return 1.0
\EndIf
\EndFunction
\end{algorithmic}
\end{algorithm}
\end{document}
答案1
问题是现代计算机没有粗体打字机字体。所以你必须选择一个字体系列,比如lmodern
。
\usepackage{lmodern}
为了增加粗体和普通字体之间的对比度,您可以选择轻量级系列。
\ttfamily\fontseries{l}\selectfont
正如 Werner 在评论中指出的那样,切换字体后,无需修改关键字,因为它们无论如何都是以粗体排版的(参见下面的代码)。
\documentclass{article}
\usepackage[ruled]{algorithm}
\usepackage[]{algorithmicx}
\usepackage[noend]{algpseudocode}
\let\oldalgorithmic\algorithmic
\renewcommand\algorithmic{\ttfamily\fontseries{l}\selectfont\oldalgorithmic}
\usepackage{lmodern}
\begin{document}
\begin{algorithm}[H]
\caption{Gaussian sampler using Taylor series}
\begin{algorithmic}
\State sigma $\gets 8 / \sqrt{2 \pi}$
\State variance $\gets$ sigma$^2$
\State \Comment{returns pdf(x) = standard Gaussian pdf}
\Function{pdf}{x}
\Return $e^{(-x^2 / 2)} / \sqrt{2 \pi}$
\EndFunction
\State \Comment{returns CDF(z) = standard Gaussian CDF using Taylor approximation}
\Function{cdf}{x}
\If{x $<$ -variance}
\Return 0.0
\ElsIf{x $>$ variance}
\Return 1.0
\EndIf
\EndFunction
\end{algorithmic}
\end{algorithm}
\end{document}