这个 \foreach 语句有什么问题?

这个 \foreach 语句有什么问题?

下面的代码

\documentclass{standalone}
\usepackage{tikz}
\usetikzlibrary{calc}

\begin{document}
\begin{tikzpicture}
  % draw two line segments
  \draw (0,0) node [below] {$s_i$} -- (2,0) node [below] {$c_i$};
  \draw (1,-2) node [below] {$s_j$} -- (3, -2) node [below] {$c_j$};

  % this works well
  \draw ($(0,0)+(0,2pt)$) -- ($(0,0)-(0,2pt)$);
  % the following \foreach does not work
  \foreach \point in {(0,0), (2,0), (1,-2), (3,-2)}
    \draw ($\point+(0,2pt)$) -- ($\point-(0,2pt)$);
\end{tikzpicture}
\end{document}

产生Runaway argument错误:

Runaway argument?
\point +(0,2pt)$) -- ($\point -(0,2pt)$);\pgffor@endhook \ifx \pgffor@assign@af
ter@code \ETC.
! Paragraph ended before \tikz@cc@parse@factor was complete.
<to be read again> 
                   \par 
l.18 

I suspect you've forgotten a `}', causing me to apply this
control sequence to too much text. How can we recover?
My plan is to forget the whole thing and hope for the best.  

原因可能很简单,但我没能找到。

答案1

列表中的元素\foreach被指定为(0,0)等,这与 Tizcalc库解析器稍后识别为真实坐标或节点名称,它将报告错误run-away-argument(根据下面@PaulGaborit 的评论澄清了这一点)

可能的解决方案是使用{0,0}(将,与数字一起作为一个元素并说\draw $(point)-(0,2pt)$)--...

\documentclass{standalone}
\usepackage{tikz}
\usetikzlibrary{calc}

\begin{document}
\begin{tikzpicture}
  % draw two line segments
  \draw (0,0) node [below] {$s_i$} -- (2,0) node [below] {$c_i$};
  \draw (1,-2) node [below] {$s_j$} -- (3, -2) node [below] {$c_j$};

  % this works well
  \draw ($(0,0)+(0,2pt)$) -- ($(0,0)-(0,2pt)$);
  % the following \foreach does work 
  \foreach \point in {{0,0}, {2,0}, {1,-2}, {3,-2}} {
    \draw ($(\point)+(0,2pt)$) -- ($(\point)-(0,2pt)$);
  }
\end{tikzpicture}
\end{document}

答案2

或者

\documentclass{standalone}
\usepackage{tikz}
\usetikzlibrary{calc}

\begin{document}
\begin{tikzpicture}
  % draw two line segments
  \draw (0,0) node [below] {$s_i$} -- (2,0) node [below] {$c_i$};
  \draw (1,-2) node [below] {$s_j$} -- (3, -2) node [below] {$c_j$};

  % this works well
  \draw ($(0,0)+(0,2pt)$) -- ($(0,0)-(0,2pt)$);
  % the following \foreach does work
  \foreach \x/\y in {0/0,2/0,1/-2,3/-2}
    \draw ($(\x,\y)+(0,2pt)$) -- ($(\x,\y)-(0,2pt)$);
\end{tikzpicture}
\end{document}

如果您将来想做这样的事情,分离坐标可能会很有用:

  \foreach \x in {...}
      \foreach \y in {...}
          ... some command with (\x,\y) ...;

相关内容