你能在 LaTex 中创建连接变量名吗?

你能在 LaTex 中创建连接变量名吗?

我想创建变量来保存像 f(x)=3x+1 这样的字符串,以便输入到考试问题中。

我可以创建 \funA、\funB 等变量。问题是如何使用 A、B 等引用它们。

\documentclass[12pt]{exam}

% conditional statements
\usepackage{xifthen}

\newcommand{\exam}{A}

\newcommand{\funA}{$s(t) = 12t^2 -7t + 16$}
\newcommand{\funB}{$s(t) = 16t^2 +3t + 10$}
\newcommand{\funC}{$s(t) = 12t^2 + t + 10.$}

\begin{document}

\begin{questions}

\question % I would like \fun\exam to return \funA when \exam = a. Sadly it doesn't 

The position of an object moving along a straight line is given by \fun\exam. Find the average velocity of the object over the interval $[1,1+h]$ where $h>0$ is a real number.

\question % this works but is a lot to write when accommodating 10 stored functions

\ifthenelse{\equal{\exam}{A}}
    {
        \newcommand{\function}{$s(t) = 12t^2 -7t + 16.$}
    }
    {
        \ifthenelse{\equal{\exam}{B}}
            {
                \newcommand{\function}{$s(t) = 16t^2 +3t + 10.$}
            }
            {
                \newcommand{\function}{$s(t) = 12t^2 + t + 10.$}
            }
    }

The position of an object moving along a straight line is given by \function\ Find the average velocity of the object over the interval $[1,1+h]$ where $h>0$ is a real number.

\end{questions}
\end{document}

答案1

TeX 允许您使用...对c引用控制s序列。此...对内的任何命令都将被展开(name\csname\endcsname\csname\endcsnameIE\csname: 替换为其含义)直到只剩下不可扩展的标记,然后 TeX 从传递给... 的内容中创建一个控制序列\endcsname

例如,如果你有\newcommand{\exam}{A},那么\csname funA\endcsname\csname fun\exam\endcsname都会扩展为\funA。你可以创建一个包装器命令以避免每次都写\csname... :\endcsname

\documentclass[12pt]{exam}

\newcommand{\exam}{A}

\newcommand{\fun}[1]{\csname fun#1\endcsname}
% or:
% \newcommand{\fun}{\csname fun\exam\endcsname}, then use just \fun instead of \fun\exam
\newcommand{\funA}{$s(t) = 12t^2 -7t + 16$}
\newcommand{\funB}{$s(t) = 16t^2 +3t + 10$}
\newcommand{\funC}{$s(t) = 12t^2 + t + 10$}

\begin{document}

\begin{questions}

\question

The position of an object moving along a straight line is given by \fun\exam. Find the average velocity of the object over the interval $[1,1+h]$ where $h>0$ is a real number.

\end{questions}
\end{document}

相关内容