tikzpicture \draw 命令中经过真正评估的 \ifnum 无法按预期工作

tikzpicture \draw 命令中经过真正评估的 \ifnum 无法按预期工作

我的最小示例如下所示:

\documentclass{article}

\usepackage{tikz}

\begin{document}
\begin{tikzpicture}
\draw (0,0) rectangle
    %\ifnum 0=1 node{My Label} \fi  % Works correctly when the value = 0
    \ifnum 1=1 node{My Label} \fi   % Fails to draw
    %node{My label}                 % What I expect when the value passed in = 1
    (4,4);
\end{tikzpicture}
\end{document}

先前的线程表明它应该可以工作:TikZ 路径内有条件吗?

我注意到这个类似的问题,不同之处在于那里的问题想要使整个部分成为条件,而我想仅使一行的一部分成为\draw条件:tikz 键内的数字条件?

报告的错误如下所示:

! Package tikz Error: Cannot parse this coordinate.

See the tikz package documentation for explanation.
Type  H <return>  for immediate help.
 ...                                              
                                              
l.10 \ifnum 1=1 n
                 ode{My Label} \fi  % Fails to draw
This error message was generated by an \errmessage
command, so I can't give any explicit help.
Pretend that you're Hercule Poirot: Examine all clues,
and deduce the truth by order and method.


! Package tikz Error: Giving up on this path. Did you forget a semicolon?.

See the tikz package documentation for explanation.
Type  H <return>  for immediate help.

如果相关的话,我在 Windows 10 上使用 MiKTeX-pdfTeX 2.9.7338 (1.40.21)(MiKTeX 2.9.7400 64 位),在 TeXStudio 2.12.22 中。

开始构建的命令是pdflatex.exe -synctex=1 -interaction=nonstopmode "tikz_error".tex

答案1

一般情况下你在路径中使用\ifnum等。然而,有些情况下 TiZ 需要一些明确的字符,或者类似的东西。在这种情况下,你可以将\ifnum内容添加到节点内容中,以使 TiZ 很开心。

\documentclass{article}

\usepackage{tikz}

\begin{document}
\begin{tikzpicture}
\draw (0,0) rectangle
    %node{\ifnum0=1\relax My Label\fi}  % Works correctly when the value = 0
    node{\ifnum1=1\relax My Label\fi}   % Works correctly
    (4,4);
\end{tikzpicture}
\end{document}

在此处输入图片描述

答案2

您可以\ifnum在执行之前展开\draw,以避免解析问题:

\documentclass{article}

\usepackage{tikz}

\begin{document}
\begin{tikzpicture}
\def\tmp{\draw (0,0) rectangle}
  \expandafter\tmp
    \ifnum 1=1 node{My Label} \fi   % Draws label
    (4,4);
  \expandafter\tmp
    \ifnum 1=2 node{My Alt Label} \fi   % Omits label
    (-4,-4);
\end{tikzpicture}
\end{document}

在此处输入图片描述

相关内容