所以我嘗試為帕斯卡三角形產生 tikzpicture。這是我到目前為止的程式碼和結果:
\begin{figure}
\centering
\begin{tikzpicture}
\foreach \n in {0,...,7}{
\foreach \k in {0,...,\n}{
\pgfmathsetmacro\nten{\n * 8}
\node[rectangle,minimum height=1cm,minimum width=1cm,draw,fill=Red!\nten] (a\k\n) at (\k-\n/2,7-\n) {$\binom{\n}{\k}$};
\pgfmathsetmacro\currbinom{\xinttheiiexpr binomial(\n,\k)\relax}
\node[rectangle,minimum height=1cm,minimum width=1cm,draw,fill=Red!\nten] (b\k\n) at (\k-\n/2+10,7-\n) {$\currbinom$};
};
};
%verbindungen
\foreach \n in {0,...,6}{
\foreach \k in {0,...,\n}{
\pgfmathsetmacro\kp{\k+1}
\pgfmathsetmacro\np{\n+1}
\draw[->] (a\k\n.center) -- (a\k\np);
};
};
\node[rectangle] (eqsign) at (5,4) {$=$};
\end{tikzpicture}
\caption{Caption}
\label{fig:pascal-tri}
\end{figure}
但是,我希望在中心之間建立連接,因此我添加了“.center”來將線條繪製到中心錨點:
\begin{figure}
\centering
\begin{tikzpicture}
\foreach \n in {0,...,7}{
\foreach \k in {0,...,\n}{
\pgfmathsetmacro\nten{\n * 8}
\node[rectangle,minimum height=1cm,minimum width=1cm,draw,fill=Red!\nten] (a\k\n) at (\k-\n/2,7-\n) {$\binom{\n}{\k}$};
\pgfmathsetmacro\currbinom{\xinttheiiexpr binomial(\n,\k)\relax}
\node[rectangle,minimum height=1cm,minimum width=1cm,draw,fill=Red!\nten] (b\k\n) at (\k-\n/2+10,7-\n) {$\currbinom$};
};
};
%verbindungen
\foreach \n in {0,...,6}{
\foreach \k in {0,...,\n}{
\pgfmathsetmacro\kp{\k+1}
\pgfmathsetmacro\np{\n+1}
\draw[->] (a\k\n.center) -- (a\k\np.center);
};
};
\node[rectangle] (eqsign) at (5,4) {$=$};
\end{tikzpicture}
\caption{Caption}
\label{fig:pascal-tri}
\end{figure}
如何修復/出了什麼問題?為什麼可以a\k\n.center
正常工作,但a\k\np.center
不行?
答案1
您不需要\pgfmathsetmacro
, 而是\pgfmathtruncatemacro
要得到整數表示形式。類似地,二項式係數值的巨集可以/應該用 定義\edef
。
順便說一句,最好定義一種樣式,而不是重複長長的選項清單:更容易管理。此外,\foreach
循環不是 PGF 語句,因此它們後面不應跟分號(您會收到大量關於;
不存在於 中的警告\nullfont
)。
\documentclass{article}
\usepackage[a4paper,margin=1cm]{geometry}
\usepackage{amsmath}
\usepackage[dvipsnames]{xcolor}
\usepackage{xintexpr}
\usepackage{tikz}
\begin{document}
\begin{figure}
\centering
\begin{tikzpicture}[
rect/.style={rectangle,minimum height=1cm,minimum width=1cm,draw,fill=Red!\nten}
]
\foreach \n in {0,...,7}{
\foreach \k in {0,...,\n}{
\pgfmathsetmacro\nten{\n * 8}
\node[rect] (a\k\n) at (\k-\n/2,7-\n) {$\binom{\n}{\k}$};
\edef\currbinom{\xinttheiiexpr binomial(\n,\k)\relax}
\node[rect] (b\k\n) at (\k-\n/2+10,7-\n) {$\currbinom$};
}
}
%verbindungen
\foreach \n in {0,...,6}{
\foreach \k in {0,...,\n}{
% \pgfmathtruncatemacro\kp{\k+1}
\pgfmathtruncatemacro\np{\n+1}
\draw[->] ({a\k\n}.center) -- ({a\k\np}.center);
}
}
\node[rectangle] (eqsign) at (5,4) {$=$};
\end{tikzpicture}
\caption{Caption}
\label{fig:pascal-tri}
\end{figure}
\end{document}