8

I'm trying to make a 7-cycle, and I expect the following code to produce a 7-cycle with one edge missing. However, the picture is completely messed up.

What happens in the lines

\pgfmathparse{\s - 1};
\draw (\s) -- (\pgfmathresult);

that I do not understand?

\documentclass{standalone}
\usepackage{tikz} 
\begin{document}
\begin{tikzpicture}[every node/.style={circle,draw}]
  \def \n {7}
  \foreach \s in {1,...,\n}
  {
    \node (\s) at ({360/\n * (\s - 1)}:1) {};
  }
  \foreach \s in {2,...,\n} 
  {
    \pgfmathparse{\s - 1};
    \draw (\s) -- (\pgfmathresult);
  }
\end{tikzpicture}
\end{document}

broken 7-cycle

9

It becomes a float from an integer. Then this float, say 3.0, is parsed as

<node name>.<angle anchor>

like (a.90) etc. You can use int(\s-1) to truncate the decimal.

5

As percusse says, the problem is that \pgfmathresult is producing 3.0 rather than 3. Rather than computing \s - 1, an alternative solution would be to use the remember key. (See section 83 of the manual.)

\begin{tikzpicture}[every node/.style={circle,draw}]
  \def \n {7}
  \foreach \s in {1,...,\n}
  {
    \node (\s) at ({360/\n * (\s - 1)}:1) {};
  }
  \foreach \s [remember=\s as \lasts (initially \n)] in {1,...,\n} 
  {
    \draw (\s) -- (\lasts);
  }
\end{tikzpicture}
5

Or don't use \pgfmathparse ...

\documentclass{standalone}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}[every node/.style={circle,draw}]
  \def \n {7}
\foreach \s in {1,...,\n}
    \node (\s) at ({360/\n * (\s - 1)}:1) {};
\foreach [count=\sx from 1] \s in {2,...,\n}% <--- 
\draw (\s) -- (\sx);
\end{tikzpicture}
\end{document}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.