Tikz:节点名称的除法和加法

Tikz:节点名称的除法和加法

我正在尝试绘制一个图形,它本质上只是一条长线,一端是三角形,另一端是正方形。我需要在三角形和正方形之间有一个长度为 26 的链。当我尝试使用下面的代码时,我收到错误“缺少数字,视为 0”。其他尝试告诉我没有名为“P0+1”的节点。我如何对节点名称进行除法、加法等操作,以便按我想要的方式迭代它们?

    \begin{tikzpicture}
    \foreach \x in {0,1,2,3,4,5,6,7,8,9,10,11,12}{
    \node (P\x) at (-\x/2,0){};
    }
    \foreach \x in {13,14,15,16,17,18,19,20,21,22,23,24,25,26}{
    \node (P\x) at ({\x-13}/2,0){};
    }

    \node (P27) at (14,1){};
    \node (P28) at (14,-1){};
    \node (P29) at (-14,1){};
    \node (P30) at (-14,-1){};
    \node (P31) at (-15,0){};


    \foreach \x in {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31}{
    \fill (P\x) circle (2pt);
    }

    \foreach \x in {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25}{
    \draw[line width=1 pt] (P\x)--(P\x+1);
    }

    \draw[line width=1 pt] (P26)--(P27);
    \draw[line width=1 pt] (P27)--(P28);
    \draw[line width=1 pt] (P28) -- (P26);
    \draw[line width=1 pt] (P13)--(P29);
    \draw[line width=1 pt] (P29)--(P30);
    \draw[line width=1 pt] (P30) -- (P31);
    \draw[line width=1 pt] (P31) -- (P13);


    \draw (0,-3) node[below]{Figure 3.4};
    \end{tikzpicture}

答案1

在某些地方,TikZ 不会解析数学,例如节点名称和其他一些地方。在循环中,您可以改用语法evaluate=<var> as <resulting var> using <formula>。在这种特定情况下,您也可以使用从 1 开始的计数器。

此外,您需要使用(...)嵌套数学并将{...}其隐藏在解析器中。因此代码变为

\begin{tikzpicture}
    \foreach \x in {0,1,2,3,4,5,6,7,8,9,10,11,12}{
    \node (P\x) at (-\x/2,0){};
    }
    \foreach \x in {13,14,15,16,17,18,19,20,21,22,23,24,25,26}{
    \node (P\x) at ({(\x-13)/2)},0){};
    }

    \node (P27) at (14,1){};
    \node (P28) at (14,-1){};
    \node (P29) at (-14,1){};
    \node (P30) at (-14,-1){};
    \node (P31) at (-15,0){};


    \foreach \x in {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31}{
    \fill (P\x) circle (2pt);
    }

    \foreach \x[evaluate=\x as \evalx using int(\x+1)] in {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25}{
    \draw[line width=1 pt] (P\x)--(P\evalx);
    }

    \draw[line width=1 pt] (P26)--(P27);
    \draw[line width=1 pt] (P27)--(P28);
    \draw[line width=1 pt] (P28) -- (P26);
    \draw[line width=1 pt] (P13)--(P29);
    \draw[line width=1 pt] (P29)--(P30);
    \draw[line width=1 pt] (P30) -- (P31);
    \draw[line width=1 pt] (P31) -- (P13);


    \draw (0,-3) node[below]{Figure 3.4};
    \end{tikzpicture}

在此处输入图片描述

相关内容