在环境中嵌入 if 语句

在环境中嵌入 if 语句

我正在尝试编写一个环境,以便我可以打开和关闭讲义上问题的答案。我还希望答案显示为红色,然后主文本在问题之后变回黑色。

我的代码如下,

\documentclass{article}
\usepackage[utf8]{inputenc}

\usepackage{geometry}
\usepackage{siunitx}
\usepackage[dvipsnames]{xcolor}
\usepackage{gensymb}

\newif\ifstudent  % This controls if it is a student version or not 

\studenttrue 

%\studentfalse

\newenvironment{answer}[1]
    {\ifstudent
    \\
    \vspace{#1}
    \\
    \else\\
    \color{red}
    }
    { 
    \color{black}\\
    \fi
    }

\begin{document}

At 18\degree C, gold has a resistance of 180 $\si{\Omega}$. When the temperature is increased, the resistance increases to 200 $\si{\Omega}$. Calculate the new temperature if the temperature coefficient of resistivity for gold is 0.0034.

\begin{answer}{40mm}
$$R_T=R_0\left[1+\alpha(T-T_0)\right]$$
\\
$$T=\frac{\frac{R_T}{R_0}-1}{\alpha}+T_0=\frac{\frac{200\;\si{\Omega}}{250\;\si{\Omega}}-1}{0.0034}+18\degree\si{C}=116\degree\si{C}$$
\end{answer}
\end{document}

<inserted text> \fi <*> main.tex不幸的是,如果我按原样运行它,我会得到一个错误。如果我将其切换到,它运行正常true

先感谢您。

答案1

我可以提出以下建议吗?

注意:以 开始和结束总是好的\par。隐藏某物的最佳方法是将其放入保存箱(这可能是它的作用\phantom)。对于环境,逻辑选择是 lrbox。在环境、组或保存箱内,您无需恢复颜色。

\documentclass{article}
\usepackage[dvipsnames]{xcolor}
\usepackage[utf8]{inputenc}

\usepackage{geometry}
\usepackage{siunitx}

\usepackage{gensymb}

\newif\ifstudent  % This controls if it is a student version or not 
\studenttrue 
%\studentfalse

\newenvironment{answer}[1]{\par
    \ifstudent\vspace{#1}\fi% #1 can only be used in first half of environments
    \begin{lrbox}{0}\minipage{\linewidth}\color{red}}%
{\endminipage\end{lrbox}%
    \ifstudent\else\usebox0\par\fi
}

\begin{document}

At 18\degree C, gold has a resistance of 180 $\si{\Omega}$. When the temperature is increased, the resistance increases to 200 $\si{\Omega}$. Calculate the new temperature if the temperature coefficient of resistivity for gold is 0.0034.

\begin{answer}{40mm}
$$R_T=R_0\left[1+\alpha(T-T_0)\right]$$
\\
$$T=\frac{\frac{R_T}{R_0}-1}{\alpha}+T_0=\frac{\frac{200\;\si{\Omega}}{250\;\si{\Omega}}-1}{0.0034}+18\degree\si{C}=116\degree\si{C}$$
\end{answer}
\hrule% show bottom ov space
\end{document}

相关内容