如何减少 tikz foreach 循环中的计数器

如何减少 tikz foreach 循环中的计数器

我有以下代码:

\documentclass[11pt]{article}
\usepackage[a4paper]{geometry}
\usepackage[utf8]{inputenc}
\usepackage[english]{babel}
\usepackage{tikz}
\usetikzlibrary{positioning}
\begin{document}
\begin{tikzpicture}[node distance = 0.5cm, auto]
\node (0) {Block 0};
\node (1) [below= of 0.south] {Block 1};
\node (2) [below= of 1.south] {Block 2};
\end{tikzpicture}
\end{document}

它打印出以下内容:

在此处输入图片描述

我尝试使用 pgf 循环执行相同操作,但不知道如何减少计数器:

\foreach \x in {0,...,2}
{
  \ifnum\x=0\relax
      \node (\x) {Block \x};
  \else
      %\prev=\x - 1 <- ???
      \node (\x) [below= of \prev.south] {Block \x};
  \fi
}

答案1

你可以使用数学:)

\foreach \x in {0,...,2}{
  \ifnum\x=0\relax
      \node (\x) {Block \x};
  \else
      \pgfmathparse{int(\x-1)}
      \node (\x) [below= of \pgfmathresult.south] {Block \x};
  \fi
}

答案2

除了使用之外,\pgfmathparse{int(…)}您还可以使用\pgfmathtruncatemacro或:

  1. eTeX\numexpr
  2. \foreach's evaluate(再次与int),
  3. \foreachremember
  4. \foreachcount起始from -1(即第\x一个减一)
  5. (推荐)chains带有 的库start chain=<chain name> going below

代码

\documentclass[tikz]{standalone}
\usetikzlibrary{positioning,chains}
\tikzset{node distance=.5cm}
\begin{document}
\begin{tikzpicture}
\foreach \x in {0,...,2}{
  \ifnum\x=0\relax
      \node (\x) {Block \x};
  \else
      \node (\x) [below=of \number\numexpr\x-1\relax] {Block \x};
  \fi
}
\end{tikzpicture}

\begin{tikzpicture}
\foreach \x[evaluate=\x as \eval using int(\x-1)] in {0,...,2}{
  \ifnum\x=0\relax
      \node (\x) {Block \x};
  \else
      \node (\x) [below=of \eval] {Block \x};
  \fi
}
\end{tikzpicture}

\begin{tikzpicture}
\foreach \x[remember=\x as \eval] in {0,...,2}{
  \ifnum\x=0\relax
      \node (\x) {Block \x};
  \else
      \node (\x) [below=of \eval] {Block \x};
  \fi
}
\end{tikzpicture}

\begin{tikzpicture}
\foreach \x[count=\eval from -1] in {0,...,2}{
  \ifnum\x=0\relax
      \node (\x) {Block \x};
  \else
      \node (\x) [below=of \eval] {Block \x};
  \fi
}
\end{tikzpicture}

\begin{tikzpicture}[start chain=going below]
\foreach \x in {0,...,2}
  \node[on chain] (\x) {Block \x};
\end{tikzpicture}
\end{document}

输出(所有解决方案)

在此处输入图片描述

相关内容