我想画一个图,但不喜欢它包含魔法常数,所以我尝试将其参数化。然而,似乎和的出现(1 + \N) / 2
必须\N - 2
以某种方式转义。正确的做法是什么?
\begin{tikzpicture}
\def \N {6}
\node (p) at ((1 + \N) / 2, -2) {};
\foreach \i in {1, ..., \N - 2, \N} {
\node (p\i) at (\i, 0) {};
}
\path foreach \i in {1, ..., \N - 2, \N} {
(p\i) -- ($(p.center)!0.5!(p.south)$)
};
\node at ($(p\N - 2)!0.5!(p\N)$) {${\cdots}$};
\end{tikzpicture}
答案1
回答原始问题
括号是语法字符,需要在数学表达式中加以保护。此外,在\node
问题的两个命令中,还有一个额外的右括号需要删除。
\documentclass{article}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
\def\N{4}
\node at ({(1 + \N)/ 2}, 0) {};
\end{tikzpicture}
\end{document}
\foreach
通过 e-TeX 计算数字来解决循环问题:
\documentclass{article}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
\def\N{4}
\foreach \i in {1, ..., \numexpr\N - 2\relax} {
% \typeout{i=\i}
\node at ({(1 + \i)/ 2}, 0) {};
}
\end{tikzpicture}
\end{document}
或者可以先计算出数字:
\pgfmathtruncatemacro\M{\N - 2}
\foreach \i in {1, ..., \M} {}
回答更新的问题
MWE 的修正评论:
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{calc}
\begin{document}
\begin{tikzpicture}
\def \N {6}
% Term put in curly braces (argument braces), because
% the outmost '(' and ')' serve as syntax characters.
\node (p) at ({(1 + \N) / 2}, -2) {};
% Workaround via e-TeX
\foreach \i in {1, ..., \numexpr\N - 2\relax, \N} {
\node (p\i) at (\i, 0) {};
}
% Another workaround by performing the calculation beforehand
\pgfmathtruncatemacro\M{\N - 2}
\path foreach \i in {1, ..., \M, \N} {
(p\i) -- ($(p.center)!0.5!(p.south)$)
};
% Inside an expandable name, pgf/TikZ math cannot be used.
% Therefore, e-TeX performs the expandable calculation.
\node at ($(p\the\numexpr\N - 2\relax)!0.5!(p\N)$) {${\cdots}$};
\end{tikzpicture}
\end{document}