TikZ 图片错误:在 \foreach 循环内没有已知名为 n1 的节点

TikZ 图片错误:在 \foreach 循环内没有已知名为 n1 的节点

我收到以下错误:

! Package pgf Error: No shape named n1 is known.

当我尝试编译该代码时。

\documentclass[border=1mm]{standalone}
\usepackage{tikz,pgfplots}
\usetikzlibrary{calc,arrows}
\usepackage{xifthen}
\begin{document}

\begin{tikzpicture}[scale=1,>=latex',line width=0.7pt]

\foreach \i/\j in {0/1,1/2,2/3,3/4,4/5,5/6,6/7,7/8}{%
\node (n\i) [draw,minimum size=1cm] at (1.7*\i,0){};
\ifthenelse{\i=7}{}{%
\draw[->] (n\i)--(n\j);}%
}
\end{tikzpicture}
\end{document}

我非常感谢你的帮助。

答案1

您可以(至少在这种情况下)尝试chain

\documentclass[tikz,border=5]{standalone}
\usetikzlibrary{chains,arrows}
\begin{document}
\begin{tikzpicture}[>=latex', ultra thick, 
  start chain, every join/.style=->, node distance=1.7]
\foreach \i in {0,...,8}
  \node (n\i) [draw, minimum size=1cm, on chain, join] {}; 
\end{tikzpicture}
\end{document}

在此处输入图片描述

答案2

我建议使用更简洁的语法。以下是另外两种方法;

\documentclass[tikz,border=1mm]{standalone}
\usetikzlibrary{arrows}
\begin{document}
\begin{tikzpicture}[scale=1,>=latex',line width=0.7pt]
\node[draw,minimum size=1cm] (n0) at (0,0) {};
\foreach \x[remember=\x as \lastx (initially 0)] in {1,...,7}{%
\node(n\x) [draw,minimum size=1cm] at (1.7*\x,0){};
\draw[<-] (n\x) -- (n\lastx);
}
\end{tikzpicture}
% If feeling adventurous
\begin{tikzpicture}[scale=1,>=latex',line width=0.7pt]
\node[draw,minimum size=1cm] (n0) at (0,0) {};
\foreach \x[remember=\x as \lastx (initially 0)] in {1,...,7}{%
\draw[<-]node[draw,minimum size=1cm,append after command=(n\x) -- (n\lastx)](n\x) at (1.7*\x,0){};
}
\end{tikzpicture}
\end{document}

如果你严格使用整数,那么你可以\ifnum\i=7\else....\fi

答案3

编辑:在不破坏\foreach声明的情况下,我们可以通过两种方式做到这一点:

\documentclass[border=1mm]{standalone}
\usepackage{tikz,pgfplots}
\usetikzlibrary{calc,arrows}
\usepackage{xifthen}
\begin{document}
\begin{tikzpicture}[>=latex',line width=0.7pt]
\foreach [evaluate=\i as \j using \i-1]\i in {0,...,7}{%
\node (n\i) [draw,minimum size=1cm] at (1.7*\i,0){};
\ifthenelse{\i=0}{}{%
\draw[->] (n\j)--(n\i);}%
}
\end{tikzpicture}
\begin{tikzpicture}[>=latex',line width=0.7pt]
\foreach \i/\j in {0/-1,1/0,2/1,3/2,4/3,5/4,6/5,7/6}{%
\node (n\i) [draw,minimum size=1cm] at (1.7*\i,0){};
\ifthenelse{\i=0}{}{%
\draw[->] (n\j)--(n\i);}%
}
\end{tikzpicture}
\end{document}

我同意杰克的评论。您可以通过将其分成\foreach两部分来实现这一点,如下所示:

\documentclass[border=1mm]{standalone}
\usepackage{tikz,pgfplots}
\usetikzlibrary{calc,arrows}
\usepackage{xifthen}
\begin{document}

\begin{tikzpicture}[scale=1,>=latex',line width=0.7pt]

\foreach \i/\j in {0/1,1/2,2/3,3/4,4/5,5/6,6/7,7/8}%
\node (n\i) [draw,minimum size=1cm] at (1.7*\i,0){};

\foreach \i/\j in {0/1,1/2,2/3,3/4,4/5,5/6,6/7,7/8}{%
\ifthenelse{\i=7}{}{%
\draw[->] (n\i)--(n\j);}%
}
\end{tikzpicture}
\end{document}

这应该可以正常工作,因为所有节点n0...n7肯定都是在上面的\foreach循环中创建的。

相关内容