定义数值变量

定义数值变量

我想在 tex 文档中定义一些变量。例如,我写入.tex类似以下内容:Our tool succeeds to validate x samples by Method A, and y samples by Method B. Thus its score is z。其中z定义为x+y,并且x(分别为y)在其他地方以数字形式实例化,例如30(分别为50)。结果,编译后文本变为Our tool succeeds to validate 30 samples by Method A, and 50 samples by Method B. Thus its score is 80

这样做的好处是,我只需要改变一些变量的值,就可以改变文本中的所有数字......

有人知道如何实现这一点吗?

答案1

\documentclass{article}

\newcommand\x{30}
\newcommand\y{50}
\begin{document}

 I would like to define some variables in a tex document. For example,
 I write in .tex something similar as: Our tool succeeds to validate \x\
 samples by Method A, and \y\ samples by Method B. Thus its score is
 \the\numexpr\x+\y\relax. 

\end{document}

输出-

在此处输入图片描述

答案2

您可以使用expl3功能,特别是xfp包,其功能\fpeval\inteval

\documentclass{article}
\usepackage{xfp}

\newcommand\x{30}
\newcommand\y{50}

\begin{document}

I would like to define some variables in a \TeX{} document. For example,
I write in \texttt{.tex} something similar as: Our tool succeeds to
validate \inteval{\x} samples by Method~A, and \inteval{\y} samples by
Method~B. Thus its score is \inteval{\x+\y}.

\end{document}

在此处输入图片描述

当然你也可以使用\x{}而不是\inteval{\x},但使用该\inteval方法你也可以这样做

\newcommand{\z}{\x+3*\y}

并使用\inteval{\z}

这假设对整数进行运算;如果您需要浮点数,则可以使用\fpeval而不是\inteval(但事情变得更加复杂)。

答案3

您可以使用计数器来实现这一点:

\newcounter{x}
\setcounter{x}{30}
\newcounter{y}
\setcounter{y}{50}
Our tool succeeds to validate \arabic{x} samples by Method A,
and \arabic{y} samples by Method B. Thus its score is 
\the\numexpr\value{x}+\value{y}.

相关内容