我正在尝试使用 Tikz 绘制一个 8*8 矩形网格,并有以下代码。但我收到错误“包 pgf 错误:没有已知的名为 v18 的形状”。注释掉的代码部分运行良好(水平线)。我看不出为什么其余部分不能工作。我是否遗漏了一些基本的东西?
\documentclass[a4paper,10pt]{article}
\usepackage[utf8]{inputenc}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}[
vertex/.style={draw,circle,thick,inner sep=0.25em}
]
%Draw lattice
\foreach \x in {0,...,7}{
\foreach \y in {0,...,7}{
\node[vertex] (v\x\y) at (\x,\y) {};
}
}
\foreach \x in {0,...,5}{
\foreach \y in {0,...,5}{
% \def\l{\the\numexpr\y+1}
\def\m{\the\numexpr\x+1}
% \draw (v\x\y) -- (v\x\l); %Horizontal lines
\draw (v\x\y) -- (v\m\y); %Vertical lines
}
}
\end{tikzpicture}
\end{document}
答案1
的目的\the\numexpr
是避免定义新的宏。只需使用它反而这些宏。
\documentclass[a4paper,10pt]{article}
\usepackage[utf8]{inputenc}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}[
vertex/.style={draw,circle,thick,inner sep=0.25em}
]
%Draw lattice
\foreach \x in {0,...,7}{
\foreach \y in {0,...,7}{
\node[vertex] (v\x\y) at (\x,\y) {};
}
}
\foreach \x in {0,...,5}{
\foreach \y in {0,...,5}{
\draw (v\x\y) -- (v\x\the\numexpr\y+1); %Horizontal lines
\draw (v\x\y) -- (v\the\numexpr\x+1\relax\y); %Vertical lines
}
}
\end{tikzpicture}
\end{document}
如果你非常想要要定义新的宏,请使用
\pgfmathtruncatemacro\l{\y+1}
\pgfmathtruncatemacro\m{\x+1}
或evaluate
钥匙
\foreach \x [evaluate=\x as \m using {int(\x+1)}] in {0,...,5}{
\foreach \y [evaluate=\y as \l using {int(\y+1)}] in {0,...,5}{
\draw (v\x\y) -- (v\x\l); %Horizontal lines
\draw (v\x\y) -- (v\m\y); %Vertical lines
}
}
然而,我想说的是,不定义新的宏是迄今为止最好的选择,因为您可能会覆盖以前的定义。
我个人也倾向于避免使用\x
and ,\y
因为它们在语法中有自己的含义calc
。相反,我建议使用\X
and\Y
代替
\documentclass[a4paper,10pt]{article}
\usepackage[utf8]{inputenc}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}[
vertex/.style={draw,circle,thick,inner sep=0.25em}
]
%Draw lattice
\foreach \X in {0,...,7}{
\foreach \Y in {0,...,7}{
\node[vertex] (v\X\Y) at (\X,\Y) {};
}
}
\foreach \X in {0,...,5}{
\foreach \Y in {0,...,5}{
\draw (v\X\Y) -- (v\X\the\numexpr\Y+1); %Horizontal lines
\draw (v\X\Y) -- (v\the\numexpr\X+1\relax\Y); %Vertical lines
}
}
\end{tikzpicture}
\end{document}
答案2
您想要\edef
,而不是\def
:
\documentclass[a4paper,10pt]{article}
\usepackage[utf8]{inputenc}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}[
vertex/.style={draw,circle,thick,inner sep=0.25em}
]
%Draw lattice
\foreach \x in {0,...,7}{
\foreach \y in {0,...,7}{
\node[vertex] (v\x\y) at (\x,\y) {};
}
}
\foreach \x in {0,...,5}{
\foreach \y in {0,...,5}{
\edef\l{\the\numexpr\y+1}
\edef\m{\the\numexpr\x+1}
\draw (v\x\y) -- (v\x\l); %Horizontal lines
\draw (v\x\y) -- (v\m\y); %Vertical lines
}
}
\end{tikzpicture}
\end{document}