使用带有参数的 newenvironments 时出错

使用带有参数的 newenvironments 时出错

我对 Latex 还很陌生,我正在尝试创建一种考试题目格式,以便尽可能少地使用 Latex。目前我写了以下代码:

\documentclass{article}

\begin{document}


\newcounter{answerCounter}
\setcounter{answerCounter}{0}


%the question environment wrapping every exam questions
\newenvironment{qst}[2]{
        \setcounter{answerCounter}{0}
        \item q#1 : #2 %the first argument of q is the question number
        \begin{itemize}
}{ \end{itemize} }

\newcommand{answ}[1]{
        \item a\value{answerCounter}: #1
        \addtocounter{answerCounter}{1}
}


\begin{itemize}
        \begin{qst}{1}{to be or not to be?}
                \answ{to be}
                \answ{not to be}
        \end{qst}

        \begin{qst}{2}{are you john doe?}
            \answ{No i'm Chuck Norris}
            \answ{maybe}
            \answ{yes}
        \end{qst}
\end{itemize}

\end{document}

我希望它显示这个:

在此处输入图片描述

我收到的错误示例如下:

! Missing number, treated as zero.
<to be read again> 
                   s
l.20 }

? 
! Missing control sequence inserted.
<inserted text> 
                \inaccessible 
l.20 }
...

什么可以帮助将错误数量减少到零?

答案1

该错误是由于缺少反斜杠造成的\newcommand{answ}

这也是\value{answerCounter}错误的:你想要一个打印的表示,这\theanswerCounter就是你所需要的。此外,计数器应该初始化为 1,而不是 0。

\documentclass{article}

\newcounter{answerCounter}

%the question environment wrapping every exam questions
\newenvironment{qst}[2]
 {\setcounter{answerCounter}{1}%
  \item q#1: #2% the first argument of q is the question number
  \begin{itemize}
 }
 {\end{itemize}}

\newcommand{\answ}[1]{%
  \item a\theanswerCounter: #1%
  \stepcounter{answerCounter}%
}

\begin{document}

\begin{itemize}
\begin{qst}{1}{to be or not to be?}
  \answ{to be}
  \answ{not to be}
\end{qst}

\begin{qst}{2}{are you john doe?}
  \answ{No i'm Chuck Norris}
  \answ{maybe}
  \answ{yes}
\end{qst}
\end{itemize}

\end{document}

在此处输入图片描述

相关内容