浮点数在新定义的环境中丢失(可能是 \vbox/\hbox 问题)

浮点数在新定义的环境中丢失(可能是 \vbox/\hbox 问题)

以下是LaTeX Error: Float(s) lost.我看到的考试班失去浮动这可能与有关\vbox。将其替换为\hbox给出Something's wrong--perhaps a missing \item。如何解决这个问题?

\documentclass{scrartcl}

\usepackage[american]{babel}

\usepackage{ifthen}
\usepackage{xparse}

\newboolean{sol}
\setboolean{sol}{false}

% solution environment
% see https://tex.stackexchange.com/questions/172404/solution-environment-via-true-false-switch?noredirect=1#172408
\NewDocumentEnvironment{solution}{O{sol}}{%
  \ifthenelse{\boolean{#1}}{\par\noindent{\sffamily\bfseries Solution}\par}{\setbox0=\vbox\bgroup}
}{\ifthenelse{\boolean{#1}}{}{\egroup}}

\begin{document}
\begin{solution}
  \begin{enumerate}
  \item foo
    \begin{figure}[!htbp]
    \end{figure}
  \end{enumerate}
\end{solution}
\end{document}

答案1

您使用了错误的工具。

\documentclass{scrartcl}

\usepackage[american]{babel}

\usepackage{ifthen}
\usepackage{environ}

\newboolean{sol}
\setboolean{sol}{false}

\NewEnviron{solution}[1][false]{%
  \csname if#1\endcsname
    \trivlist
    \item\relax\textbf{Solution.}\enspace
    \BODY
    \endtrivlist
  \fi
}


\begin{document}
\begin{solution}
  \begin{enumerate}
  \item foo
    \begin{figure}[!htbp]
    \end{figure}
  \end{enumerate}
\end{solution}

\begin{solution}[true]
  \begin{enumerate}
  \item foo
    \begin{figure}[!htbp]
    \centering
    \Huge A
    \caption{An A}
    \end{figure}
  \end{enumerate}
\end{solution}
\end{document}

相关内容