使用 \foreach 进行奇怪的转换

使用 \foreach 进行奇怪的转换

我想在几个点之间画线。由于这有点重复,我想尝试一下 for 循环。但是,整个图片有一些奇怪的偏移,每次 for 循环迭代都会添加,这不是故意的,我不明白。

首先,我将在我的图片中使用一些定义。

\def\l{2}
\def\b{2}
\def\n{3}
\def\delta{(\n-1)*(\l+\b)-\l-2}

\pgfmathdeclarefunction{x}{1}{
    \pgfmathparse{\delta-(#1-1)*(\b+\l)}
}

\pgfmathdeclarefunction{y}{1}{
    \pgfmathparse{\delta-(#1-1)*(\b+\l)+\l}
}

以下是按预期工作的 MWD:

\begin{tikzpicture}[every node/.style={black,above right}]
\coordinate (P) at (0,0);
\coordinate (x1) at ({x(1)},1);
\coordinate (y1) at ({y(1)},1);

\coordinate (x2) at ({x(2)},1);
\coordinate (y2) at ({y(2)},1);

\coordinate (x3) at ({x(3)},1);
\coordinate (y3) at ({y(3)},1);

\draw[dotted] (P) -- (x1);
\draw (x1) -- (y1);
\draw[dotted] (y1) -- (P);

\draw[dotted] (P) -- (x2);
\draw (x2) -- (y2);
\draw[dotted] (y2) -- (P);

\draw[dotted] (P) -- (x3);
\draw (x3) -- (y3);
\draw[dotted] (y3) -- (P);
\end{tikzpicture}

结果如下:

预期结果

而 for 循环版本

\begin{tikzpicture}[every node/.style={black,above right}]
    \coordinate (P) at (0,0);

    \foreach \i in {1,...,\n}
    {
        \coordinate (x) at ({x(\i)},1);
        \coordinate (y) at ({y(\i)},1);
        \draw[dotted] (P) -- (x);
        \draw (x) -- (y);
        \draw[dotted] (y) -- (P);
    }
\end{tikzpicture}

产生这个:

奇怪的偏移

我猜测,发生这种情况的原因可能是一些奇怪的范围问题。但是我很少使用 tikz,所以我不知道如何修复这个问题/实际问题是什么。任何帮助都将不胜感激。

谢谢。

答案1

末尾有很多空格。使用

\pgfmathdeclarefunction{x}{1}{%
    \pgfmathparse{\delta-(#1-1)*(\b+\l)}%
}
\pgfmathdeclarefunction{y}{1}{%
    \pgfmathparse{\delta-(#1-1)*(\b+\l)+\l}%
}   

在此处输入图片描述

答案2

只需创建两个循环就足够了,第一个循环定义坐标,第二个循环使用它们。

截屏

\documentclass[12pt]{article}
\usepackage{tikz}

\def\l{2}
\def\b{2}
\def\n{3}
\def\delta{(\n-1)*(\l+\b)-\l-2}

\pgfmathdeclarefunction{x}{1}{
    \pgfmathparse{\delta-(#1-1)*(\b+\l)}
}

\pgfmathdeclarefunction{y}{1}{
    \pgfmathparse{\delta-(#1-1)*(\b+\l)+\l}
}


\begin{document}
\begin{tikzpicture}[every node/.style={black,above right}]
    \coordinate (P) at (0,0);

    \foreach \i in {1,...,\n}
    {
        \coordinate (x\i) at ({x(\i)},1);
        \coordinate (y\i) at ({y(\i)},1);
    }
        \foreach \i in {1,...,\n}
    {
        \draw[dotted] (P) -- (x\i);
        \draw (x\i) -- (y\i);
        \draw[dotted] (y\i) -- (P);
    }
\end{tikzpicture}


\end{document}

相关内容