我想知道如何在某个宏中正确检查均匀性或奇数性。我玩过一些fp
包pgfmath
,但似乎我对 TeX 不够熟悉,无法正确执行此操作。下面是一个示例,我尝试检查 2 个参数的均匀性:
\documentclass{article}
\usepackage{tikz}
\def\IfEven#1{\pgfmathparse{int(mod(#1,2))}\ifnum\pgfmathresult=0}
\newcommand{\parity}[2]{%
\def\x{#1}%
\def\y{#2}%
\IfEven{\x}%
\IfEven{\y}%
{\x} and {\y} are even.%
\else%
{\x} is even and {\y} is odd.%
\fi%
\else%
\IfEven{\y}%
{\x} is odd and {\y} is even.%
\else%
{\x} and {\y} are odd.%
\fi%
%% If I put a second \fi here I got an error 'Extra \fi.', otherwise
%% it compiles and works fine but there are two warnings:
%% (\end occurred when \ifnum on line 28 was incomplete)
%% (\end occurred when \ifnum on line 26 was incomplete)
}
\begin{document}
\parity{0}{7}\\
\parity{3}{3}\\
\parity{2}{6}\\
\parity{1}{4}\\
\end{document}
我确实知道我应该写第二个\fi
(但它无法编译)。否则,它会编译,显示我期望的内容,但我对警告感到很不舒服……我想我使用这个宏的次数越多,我收到的警告就越多。
所以如果您有任何建议......
答案1
当跳过条件文本时,TeX 仍会跟踪\if...
、\else
和\fi
。
当您调用 时\parity{1}{0}
,第一个\IfEven
被扩展,留\ifnum
在输入流中。由于条件返回 false,内部\IfEven
不会被扩展,并且第一个\else
与 匹配\ifnum
。
有一个古老的诀窍可以解决此问题,即使用\if
。这个诀窍据说是大巫师本人发明的。
\documentclass{article}
\usepackage{tikz}
\def\IsEven#1{%
TT\fi
\pgfmathparse{int(mod(#1,2))}%
\ifnum\pgfmathresult=0
}
\newcommand{\parity}[2]{%
\if\IsEven{#1}%
\if\IsEven{#2}%
#1 and #2 are even.%
\else%
#1 is even and #2 is odd.%
\fi
\else
\if\IsEven{#2}%
#1 is odd and #2 is even.%
\else
#1 and #2 are odd.%
\fi
\fi
}
\begin{document}
\parity{0}{7}
\parity{3}{3}
\parity{2}{6}
\parity{1}{4}
\end{document}
这样,总有一个条件来做出正确的平衡。当它处于非跳过文本中时,\if
触发扩展\IsEven
将留下
\if TT\fi
<code>
\ifnum...
并且条件将再次平衡。该\if TT\fi
部分将扩展到零。
答案2
不要做
\def\IfEven#1{\pgfmathparse{int(mod(#1,2))}\ifnum\pgfmathresult=0}
因为这样的语法会留下尾随\else
并且\fi
与 tex-primitive 不匹配\if
。
使用\if
语法或使用参数语法
\pgfmathparse{int(mod(#1,2))}%
\ifnum\pgfmathresult=0
yes
\else
no
\fi
或者
\def\IfEven#1#2#3{\pgfmathparse{int(mod(#1,2))}\ifnum\pgfmathresult=0 %need this space!
#2%
\else
#3%
\fi}
然后
\IfEven{\x}{yes}{no}