Quiz with answer (please recommend me a format of TeX document)

countersexercisesmacros

I want to make a quiz using TeX that "looks like"

Problem 1) Let $f(x)=x^2$. Evaluate $f'(1)$.

Problem 2) Let $A$ be a matrix such that
$$A=\begin{bmatrix}3&1\0&1\end{bmatrix}$$ What is the value of $|A|$?

Answer1) 2

Answer2) 3

And I made a TeX file "written as"

\documentclass{article}

\usepackage{amsmath,amssymb}

\newcounter{num}
\newcommand{\prob}{\par\bigskip\bigskip\noindent\refstepcounter{num}\textbf{Problem \arabic{num}) }}
\newcommand{\ans}{\par\bigskip\bigskip\noindent\refstepcounter{num}\textbf{Answer \arabic{num}) }}

\begin{document}
\prob
Let $f(x)=x^2$.
Evaluate $f'(1)$.
 
\prob
Let $A$ be a matrix such that
$$A=\begin{bmatrix}3&1\\0&1\end{bmatrix}.$$
What is the value of $|A|$?

\setcounter{num}{0}

\ans
2
\ans
3
\end{document}

It prints the result pretty well, except for the fact that the problem statements and answers are separated.

I want to type answer 1 just after problem 1, which would prevent many kinds of errors.

How can I fix my code?

Best Answer

With the options answerdelayed of exercise package, you can write the answer near the problem in your code, but print them only when you like with \shipoutAnswer.

I think exercise is the simplest package for exercises, if you find its documentation lengthy, I don't know what you would say of TikZ one! :D

\documentclass{article}
\usepackage{amsmath,amssymb}
\usepackage[lastexercise,answerdelayed]{exercise}
\renewcommand{\ExerciseName}{Problem}
\renewcommand{\ExerciseHeader}{\noindent\ExerciseName\ \ExerciseHeaderNB)}
\renewcommand{\AnswerName}{Answer}
\renewcommand{\AnswerHeader}{\noindent\AnswerName\ \ExerciseHeaderNB)\ }

\begin{document}
\begin{Exercise}
    Let $f(x)=x^2$.
    Evaluate $f'(1)$.
\end{Exercise}
\begin{Answer}
    2
\end{Answer}
\begin{Exercise}
    Let $A$ be a matrix such that
    \[A=\begin{bmatrix}3&1\\0&1\end{bmatrix}.\]
    What is the value of $|A|$?
\end{Exercise}
\begin{Answer}
    3
\end{Answer}
\shipoutAnswer
\end{document}

enter image description here

Edit: if you prefer commands instead of environments:

\documentclass{article}
\usepackage{amsmath,amssymb}
\usepackage[lastexercise,answerdelayed]{exercise}
\renewcommand{\ExerciseName}{Problem}
\renewcommand{\ExerciseHeader}{\noindent\ExerciseName\ \ExerciseHeaderNB)}
\renewcommand{\AnswerName}{Answer}
\renewcommand{\AnswerHeader}{\noindent\AnswerName\ \ExerciseHeaderNB)\ }

\newcommand{\prob}[1]{\begin{Exercise}#1\end{Exercise}}
\newcommand{\ans}[1]{\begin{Answer}#1\end{Answer}}

\begin{document}
\prob{Let $f(x)=x^2$.
    Evaluate $f'(1)$.}
\ans{2}
\prob{Let $A$ be a matrix such that
    \[A=\begin{bmatrix}3&1\\0&1\end{bmatrix}.\]
    What is the value of $|A|$?}
\ans{3}
\shipoutAnswer
\end{document}
Related Question