使用 multicols 和 lstlisting 格式化列

使用 multicols 和 lstlisting 格式化列

我想让下图中的代码显示在标题后面。我知道我之前问过这个问题,但它详细说明了枚举项。我可以得到一些帮助让它看起来更好吗?

在此处输入图片描述

\documentclass[a4paper]{article}

\usepackage[english]{babel}
\usepackage[utf8]{inputenc}
\usepackage{amsmath}
\usepackage{graphicx}
\usepackage[colorinlistoftodos]{todonotes}
\usepackage[mathscr]{euscript}
\usepackage{enumerate}
\usepackage{amsfonts}
\usepackage{multicol}
\usepackage{listings}

\begin{document}

\parindent0pt

\newtheorem{prob}{Problem}

\setcounter{prob}{3}
\begin{prob}
Write a python function $sumsq$ that takes as input a positive integer $n$ and returns the sum of the squares of the integers in the list $1, \dots, n$. Print  out the values of $sumsq(n)$ for $n=1,\dots, 20$
\end{prob}

\begin{multicols}{2}
\textbf{Code for Problem 4:} 
\begin{lstlisting}
def sumsq(n):
    total = 0
    for i in range(1,n+1):
        total = total+(i**2)
    return(total)
\end{lstlisting}

\columnbreak

\textbf{Printout of Code for Problem 4:}
\begin{lstlisting}
>>> for i in range(1,20): sumsq(i)

1
5
14
30
55
91
140
204
285
385
506
650
819
1015
1240
1496
1785
2109
2470
\end{lstlisting}
\end{multicols}

\end{document}

答案1

我建议您使用minipages 而不是multicol环境。

示例输出

\documentclass[a4paper]{article}

\usepackage[english]{babel}
\usepackage[utf8]{inputenc}
\usepackage{listings}

\begin{document}

\parindent0pt

\newtheorem{prob}{Problem}

\setcounter{prob}{3}
\begin{prob}
Write a python function $sumsq$ that takes as input a positive integer $n$ and returns the sum of the squares of the integers in the list $1, \dots, n$. Print  out the values of $sumsq(n)$ for $n=1,\dots, 20$
\end{prob}

\begin{center}
  \begin{minipage}[t]{0.45\linewidth}
    \textbf{Code for Problem 4:}
\begin{lstlisting}
def sumsq(n):
    total = 0
    for i in range(1,n+1):
        total = total+(i**2)
    return(total)
\end{lstlisting}
  \end{minipage}
  \qquad
  \begin{minipage}[t]{0.47\linewidth}
    \textbf{Printout of Code for Problem 4:}
\begin{lstlisting}
>>> for i in range(1,20): sumsq(i)

1
5
14
30
55
91
140
204
285
385
506
650
819
1015
1240
1496
1785
2109
2470
\end{lstlisting}
  \end{minipage}
\end{center}

\end{document}

您应该适当调整宽度。

相关内容