在单个命令调用中显示变量名称、测量单位和值

在单个命令调用中显示变量名称、测量单位和值

我正在使用该fp软件包编写力学课程作业动态计算数值。以下是一些示例代码:

\documentclass{article}
\usepackage[nomessages]{fp}  % http://ctan.org/pkg/fp
\begin{document}

\section{Requirements}
\FPset{P_output_kW}{11}
\FPset{n_output_max_rpm}{5000}

P_output_kW = \FPprint{P_output_kW} kW
n_output_max_rpm = \FPprint{n_output_max_rpm} rpm
\end{document}

显然,我试图按名称、值和测量单位打印每个分配的变量。首先,上述代码无法编译并出现错误:

! Missing $ inserted.

我想在单个命令(带有单个参数)中调用这两个操作:

  • 打印变量名称,然后=
  • 打印变量值

如何才能实现这一点呢?

答案1

下面以打字机字体设置变量名,数字\FPprint和单位取自变量名:

\documentclass{article}
\usepackage[nomessages]{fp}  % http://ctan.org/pkg/fp

\newcommand*{\VarOutput}[1]{%
  \begingroup
    \fontencoding{T1}%
    \fontfamily{lmvtt}\selectfont % variable typewriter font
    % alternative: \ttfamily
    \detokenize{#1}% make _ to character
  \endgroup
  ~=~%
  \FPprint{#1}%
  \,%
  \ExtractUnit{#1}%
}
\newcommand*{\ExtractUnit}[1]{%
  \expandafter\ExtractUnitAux\detokenize{#1_}\relax
}
\begingroup
  \catcode`\_=12 %
  \gdef\ExtractUnitAux#1_#2\relax{%
    \ifx\\#2\\%
      #1
    \else
      \ExtractUnitAux#2\relax
    \fi
  }
\endgroup

\begin{document}
\section{Requirements}
\FPset{P_output_kW}{11}
\FPset{n_output_max_rpm}{5000}

\VarOutput{P_output_kW}\\
\VarOutput{n_output_max_rpm}
\end{document}

结果

答案2

这使用 \csname。

\documentclass{article}
\usepackage{showframe}
\usepackage{siunitx}
\usepackage{pgfmath}
\parindent=0pt

\newcommand{\FPset}[2]% #1 = varaible name, #2 = value
  {\expandafter\gdef\csname FPV#1\endcsname{#2}}

\newcommand{\FPunit}[2]% #1 = variable name, #2 = units
  {\expandafter\gdef\csname FPU#1\endcsname{#2}}

\newcommand{\FPmacro}[2]% #1 = variable name, #2 = macro to store value
  {\edef #2{\csname FPV#1\endcsname}}

\newcommand{\FPprint}[1]% #1 = variable name
  {#1 $=$ \num{\csname FPV#1\endcsname} \si{\csname FPU#1\endcsname}}

\begin{document}
\FPset{power}{5}
\FPunit{power}{\si{\kilo\watt}}% predefined from sciunitx
\FPprint{power}

\FPset{time}{2}
\FPunit{time}{\si{\hour}}
\FPprint{time}\par

\FPmacro{power}{\x}
\FPmacro{time}{\t}
\pgfmathparse{\x*\t}
\FPset{energy}{\pgfmathresult}
\FPunit{energy}{\si{\kilo\watt\hour}}
\FPprint{energy}
\end{document}

单位

相关内容