像比特币白皮书一样突出显示 Java 代码

像比特币白皮书一样突出显示 Java 代码

在比特币白皮书中(https://bitcoin.org/bitcoin.pdf) 第 7 页有一个 C 代码片段。样式、字体和大小非常整洁和合适。我如何在 TexStudio 中将这种样式应用于我的 Java 代码(我正在使用 TexLive)?

这是我的 Java 代码:

import java.math.*;

public class successAttackerProbability {

public double calculateSuccessProbability(double q, int z) {
    int i, k;
    double p = 1.0 - q;
    double lambda = z * (q / p);
    double sum = 1.0;
    for (k = 0; k <= z; k++) {
        double poisson = Math.pow(Math.E, -lambda);

        for (i = 1; i <= k; i++)
            poisson *= lambda / i;
        sum -= poisson * (1 - Math.pow(q / p, z - k));

    }
    System.out.println(sum);
    return sum;

}

public static void main(String[] args) {
    successAttackerProbability successAttackerProbability = new successAttackerProbability();
    successAttackerProbability.calculateSuccessProbability(0.1, 1); // q =0.1 and z = 1
    successAttackerProbability.calculateSuccessProbability(0.1, 2);
    // ..
    successAttackerProbability.calculateSuccessProbability(0.1, 10);

}

}

答案1

这看起来像是简单的逐字记录,或者包含设置的listings包。basicstyle\ttfamily

例子

\documentclass[a4paper]{article}
\usepackage[margin=3cm]{geometry}
\usepackage{listings}
\lstset{
  language=JAVA,
  basicstyle=\ttfamily\small,
%  columns=flexible,
  breaklines,
  breakatwhitespace,
}
\begin{document}

\begin{lstlisting}
import java.math.*;

public class successAttackerProbability {

public double calculateSuccessProbability(double q, int z) {
    int i, k;
    double p = 1.0 - q;
    double lambda = z * (q / p);
    double sum = 1.0;
    for (k = 0; k <= z; k++) {
        double poisson = Math.pow(Math.E, -lambda);

        for (i = 1; i <= k; i++)
            poisson *= lambda / i;
        sum -= poisson * (1 - Math.pow(q / p, z - k));

    }
    System.out.println(sum);
    return sum;

}

public static void main(String[] args) {
    successAttackerProbability successAttackerProbability = new successAttackerProbability();
    successAttackerProbability.calculateSuccessProbability(0.1, 1); // q =0.1 and z = 1
    successAttackerProbability.calculateSuccessProbability(0.1, 2);
    // ..
    successAttackerProbability.calculateSuccessProbability(0.1, 10);

}
\end{lstlisting}

\end{document}

listings详细信息请参阅包装手册。

相关内容