3

It seems that in a tikz-foreach-loop mathematical expressions are not evaluated correctly:

\documentclass{minimal}
\usepackage{tikz}

\begin{document}

\begin{tikzpicture}
\foreach \c [count=\i] in {0,1,...,{floor(9/4)}}
\node at (\i,0) {\c};
\end{tikzpicture}

\end{document}

This yields the strange output:

0 1 ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?

Any ideas how to fix this?

3
  • 1
    Please EDIT to show code, which compiles. By doing so you also show us an important detail: your preamble. Thanks
    – MS-SPO
    Jul 16, 2023 at 7:42
  • 1
    @MS-SPO done... Jul 16, 2023 at 7:51
  • 2
    Please search here for floor. As far as I can see, it‘s not intended to calculate, which would require a missing library. Also have a look at tikz.dev/math-parsing#autosec-7653 in case you have to dive a little inti tikz internals.
    – MS-SPO
    Jul 16, 2023 at 8:10

2 Answers 2

4

Adaptations

  • use \pgfmathsetmacro{\n}{floor(9/4)} to save the result as \n
  • \n can than be used as upper limit of the for loop

Code

\documentclass{minimal}
\usepackage{tikz}

\begin{document}

\begin{tikzpicture}
    \pgfmathsetmacro{\n}{floor(9/4)}
    \foreach \c [count=\i] in {0,1,...,\n}
    \node at (\i,0) {\c};
\end{tikzpicture}

\end{document}

Result

enter image description here

3
  • 2
    Awesome, thanks! The other answer is equally nice, but I can accept only one. Jul 16, 2023 at 8:32
  • 1
    This should also work without loading \usetikzlibrary{calc}. Jul 16, 2023 at 8:54
  • @JasperHabicht Oh, right. I removed it.
    – dexteritas
    Jul 16, 2023 at 15:19
7

The parser trips over the fact that the floor starts with a letter, and hence doesn't find the floor(9/4) to be a numeric.

If you add parse=true to \foreach's options list, and prefix the floor expression with a number such that \foreach actually thinks that's a number, you get what you wanted (without a user facing temporary assignment):

\documentclass[border=3.14,tikz]{standalone}

\begin{document}

\begin{tikzpicture}
\foreach \c [count=\i,parse=true] in {0,1,...,1*floor(9/4)}
  \node at (\i,0) {\c};
\end{tikzpicture}

\end{document}

enter image description here

1
  • 1
    Although, I like this answer a lot, I decided to accept the other answer. Thank you! Jul 16, 2023 at 8:33

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .