在 tikz foreach 列表中进行计算

在 tikz foreach 列表中进行计算

如果我说

\documentclass{article}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
\def\I{2}
\foreach \i in { \I+1, ..., 20 }
  \node at (\i,10) {+};
\end{tikzpicture}
\end{document}

我明白了

! Illegal unit of measure (pt inserted).
<to be read again> 
                   +
l.560     \node[anchor=center] at (\i,10) {$+$};

如何在 foreach...范围的界限内进行算术运算?

答案1

的一些可能性foreach。对于你的情况,你可以尝试第一个

\documentclass[11pt]{scrartcl}
\usepackage{tikz}


\begin{document} 
  \def\I{2}   
\begin{tikzpicture}
\foreach \i   [evaluate=\i] in {\I+1,...+1,19+1}
  \node[anchor=center] at (\i,0) {$\i$};
\end{tikzpicture} 

\begin{tikzpicture}
\foreach \i   [evaluate=\i as \j using \i+1] in {\I,...,10}
  \node[anchor=center] at (\j,0) {$\j$};
\end{tikzpicture} 

\begin{tikzpicture}
\foreach \i   [evaluate=\i as \j using \i*\i] in {\I,...,4}
  \node[anchor=center] at (\j,0) {$\j$};
\end{tikzpicture}   
\end{document} 

答案2

使用 eTeX,您可以使用\numexpr

\documentclass{article}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
  \def\I{2}
  \foreach \i in {\number\numexpr\I + 1\relax, ..., 20 }
  \node[anchor=center] at (\i,10) {$+$};
\end{tikzpicture}
\end{document}

答案3

您可以使用\pgfmathsetmacro{\Start}{\I+1}来计算起点,然后\Start使用\foreach

\documentclass{article}
\usepackage{tikz}

\begin{document}
\begin{tikzpicture}
\def\I{2}
\pgfmathsetmacro{\Start}{\I+1}
\foreach \i in { \Start, ..., 20 }
  \node[anchor=center] at (\i,10) {$+$};
\end{tikzpicture}
\end{document}

相关内容