我正在使用该etoolbox
包检查一些变量。我可以用\ifnumless{a}{b}{True}{False}
它来检查“a”是否小于“b”,如果为真则输出“True”,如果为假则输出“False”。但是我如何检查两个条件是否满足?例如:
IF a < b AND x > 100
DO "True"
ELSE "False"
答案1
您可以在测试中使用逻辑组合and
和or
\ifboolexpr
\ifboolexpr{%
test {\ifnumless{a}{b}}
and
test{\ifnumgreater{x}{100}}
}{YES}{NO}
有关详细信息,请参阅文档(第 3.6.5 节)。
我想举个例子。
\documentclass{article}
\usepackage{etoolbox}
\newcounter{a}\newcounter{b}\newcounter{x}
\newrobustcmd*\setabx[3]{%
\setcounter{a}{#1}\setcounter{b}{#2}\setcounter{x}{#3}%
}
\newrobustcmd*\iftwocont{%
\ifboolexpr{%
test {\ifnumless{\value{a}}{\value{b}}}
and
test{\ifnumgreater{\value{x}}{100}}%
}%
}
\begin{document}
\setabx{1}{1}{1}
\iftwocont{$a<b$ and $x>100$}{The logical combination is false}
\setabx{5}{10}{300}
\iftwocont{$a<b$ and $x>100$}{The logical combination is false}
\end{document}
结果:
The logical combination is false
a < b and x > 100
答案2
下面的代码只占用了 1% 的运行时间,\ifboolexpr
并且可以进行算术运算。可以将其改为处理实数。
\documentclass{article}
\usepackage{catoptions}
\makeatletter
\def\numtest#1and#2#{%
\ifnum\numexpr\cpt@numlt\cpt@numgt\cpt@numeq#1%
\cpt@removetonnil<=>\cpt@nnil\relax
\ifnum\numexpr\cpt@numlt\cpt@numgt\cpt@numeq#2%
\cpt@removetonnil<=>\cpt@nnil\relax
\expandafter\expandafter\expandafter\@firstoftwo
\else
\expandafter\expandafter\expandafter\@secondoftwo
\fi
\else
\expandafter\@secondoftwo
\fi
}
\makeatother
\numtest 1+2<3+2 and 4+3>2+3{true}{false}
\numtest 1+2<3+2 and 2+3>2+3{true}{false}
\numtest 1+2+4>3+2 and 2+3+4=2+3+5+3{true}{false}