在定义数字后分配长度单位

在定义数字后分配长度单位

我有一个 latex,它可以进行一些计算,但是函数不适用于长度。我希望能够为数学输出分配单位。以下操作无需分配单位即可成功。

\documentclass{article}
\usepackage{calculator}
\usepackage{xparse}

% #1 is unitless length
% #2 is angle in degrees
% #3 is for output selection
\NewDocumentCommand\DoMath{m m m}
{
\COPY{#1}{\a}
\COPY{#2}{\t}
\def\choice{#3}
\DEGREESSIN{\t}{\st}
\DEGREESCOS{\t}{\ct}
\DEGREESTAN{\t}{\tt}
\DIVIDE{\a}{\tt}{\b}
\DIVIDE{\a}{\st}{\c}


\ifnum #3=1
    \a
\else
    \ifnum #3=2
        \b
    \else
        \ifnum #3 =3
            \c
        \else
            \ifnum #3 =4
                \t
            \else
                \a
            \fi
        \fi
    \fi
\fi
}


\NewDocumentCommand\DoMathTest{m m}
{
\DoMath{#1}{#2}{1} %return a (height)

\DoMath{#1}{#2}{2} % return b (width)

\DoMath{#1}{#2}{3} % return c (hypotenuse)

\DoMath{#1}{#2}{4} % return t (angle)

\DoMath{#1}{#2}{5} % test incorrect selection returns a (height)

}


\begin{document}
\DoMathTest{10}{30} % this function succeeds
\end{document}

输出是

10

17.32106

20.00061

三十

10

以下失败

\documentclass{article}
\usepackage{calculator}
\usepackage{xparse}

% #1 is unitless length
% #2 is angle in degrees
% #3 is for output selection
\NewDocumentCommand\DoMath{m m m}
{
\COPY{#1}{\a}
\COPY{#2}{\t}
\def\choice{#3}
\DEGREESSIN{\t}{\st}
\DEGREESCOS{\t}{\ct}
\DEGREESTAN{\t}{\tt}
\DIVIDE{\a}{\tt}{\b}
\DIVIDE{\a}{\st}{\c}


\ifnum #3=1
    \a
\else
    \ifnum #3=2
        \b
    \else
        \ifnum #3 =3
            \c
        \else
            \ifnum #3 =4
                \t
            \else
                \a
            \fi
        \fi
    \fi
\fi
}



\NewDocumentCommand\DoMathTest{m m m}
{

\newlength{\ti}
%fails around here
\setlength{\ti}{{\DoMath{#1}{#2}{1}}#3} %return a
\ti

\DoMath{#1}{#2}{2} % return b

\DoMath{#1}{#2}{3} % return c

\DoMath{#1}{#2}{5} % test incorrect selection return's a

}

\begin{document}
\DoMathTest{10}{30}{in} % this function succeeds
\end{document}

答案1

您的\DoMath命令不是完全可扩展的,因此\setlength会严重失败。

您可以改用可扩展浮点命令expl3

\documentclass{article}

% #1 is unitless length
% #2 is angle in degrees
% #3 is for output selection

\ExplSyntaxOn

\NewExpandableDocumentCommand\DoMath{m m m}
 {
  \int_case:nnF { #3 }
   {
    {1}{#1}
    {2}{\fp_eval:n { (#1)/tand(#2) }}
    {3}{\fp_eval:n { (#1)/sind(#2) }}
    {4}{#2}
   }
   {#1}
 }

\ExplSyntaxOff

\NewDocumentCommand\DoMathTest{m m}{%
  \DoMath{#1}{#2}{1}% return a (height)

  \DoMath{#1}{#2}{2}% return b (width)

  \DoMath{#1}{#2}{3}% return c (hypotenuse)

  \DoMath{#1}{#2}{4}% return t (angle)

  \DoMath{#1}{#2}{5}% test incorrect selection returns a (height)
}

\newlength{\ti}

\NewDocumentCommand\DoMathTestAgain{m m m}{%
  \setlength{\ti}{\DoMath{#1}{#2}{1}#3}% return a
  \the\ti
}

\begin{document}

\DoMathTest{10}{30}

\DoMathTestAgain{10}{30}{in}

\end{document}

在此处输入图片描述

相关内容