Search code examples
latexpdflatextikz

Draw a grid with 32 cells, intermediate rectangles does not show up


I would like to draw a figure describing the floating-point IEEE754 specification. Doing so, I tried to draw a grid with 32 rectangles. (I then figured out there is a grid command). Here is a MWE for 4 cells:

\documentclass{standalone}
\usepackage[utf8]{inputenc}
\usepackage{tikz}

\begin{document}
\begin{tikzpicture}
    \newcommand{\width}{1}
    \newcommand{\height}{2}
    \foreach \x in {0, 1}{
    \draw (\x, 0) rectangle (\x+\width, \height);
    }
    \foreach \x in {2, 3}{
    \draw (\x, 0) rectangle (\x+\width, \height);
    }
\end{tikzpicture}
\end{document}

I used two foreach. I could merge these into one, but I then obtain only the rectangles on the far left and far right side, not the four rectangles as in the first MWE. Why is it so ?

\begin{tikzpicture}
    \newcommand{\width}{1}
    \newcommand{\height}{2}
    \foreach \x in {0, 4}{
    \draw (\x, 0) rectangle (\x+\width, \height);
    }
\end{tikzpicture}

Solution

  • By using \foreach \x in {0, 4} your list literally just has these two values, no intermediate values.

    If you like to include intermediate steps, you can use \foreach \x in {0,...,3}

    \documentclass{standalone}
    \usepackage[utf8]{inputenc}
    \usepackage{tikz}
    
    \begin{document}
    
    \begin{tikzpicture}
        \newcommand{\width}{1}
        \newcommand{\height}{2}
        \foreach \x in {0,...,3}{
        \draw (\x, 0) rectangle (\x+\width, \height);
        }
    \end{tikzpicture}
    \end{document}
    

    enter image description here