我正在使用两个包 - 练习和列表。我正在尝试为包含源代码的答案创建一个环境“codeAnswer”,这样我就不必这样做了 -
\begin{Answer}
\begin{lstlisting}
<code answer>
\end{lstlisting}
\end{Answer}
但它不起作用。一如既往,任何帮助都值得感激 :) 下面是有缺陷的代码:
\documentclass[11pt]{article}
\usepackage[answerdelayed]{exercise}
\usepackage{listings}
%need to fix
\newenvironment{codeAnswer}
{
\begin{Answer}
\begin{lstlisting}
}
{
\end{lstlisting}
\end{Answer}
}
\begin{document}
\begin{Exercise}
What is 2 + 3?
\end{Exercise}
\begin{Answer}
5
\end{Answer}
\begin{Exercise}
Write a piece of code that divides 5 by 2 and stores in an integer $x$.
\end{Exercise}
%Following commented part works fine
%\begin{Answer}
%\begin{lstlisting}
%int x = 5/2;
%\end{lstlisting}
%\end{Answer}
%FOLLOWING DOESN'T WORK
\begin{codeAnswer}
int x = 5/2;
\end{codeAnswer}
\shipoutAnswer
\end{document}
答案1
使用\lstnewenvironment
,但使用\Answer
和\endAnswer
:
\documentclass[11pt]{article}
\usepackage[answerdelayed]{exercise}
\usepackage{listings}
\lstnewenvironment{codeAnswer}[1][]
{\Answer\lstset{#1}}
{\endAnswer}
\begin{document}
\begin{Exercise}
What is 2 + 3?
\end{Exercise}
\begin{Answer}
5
\end{Answer}
\begin{Exercise}
Write a piece of code that divides 5 by 2 and stores in an integer $x$.
\end{Exercise}
\begin{codeAnswer}
int x = 5/2;
\end{codeAnswer}
\shipoutAnswer
\end{document}
您还可以使用它
\begin{codeAnswer}[<options for lstlisting>]