
如何從同一變數增加變數?
\pgfmathsetmacro\S{5};
\pgfmathsetmacro\S{\S + 1};% not working
我該如何解決這個問題?我需要在某些條件下用作線座標增量的計數器。
更新
\pgfmathsetmacro\cA{0};
\newcounter{cB}
\foreach \x in {1,...,10}
{
\pgfmathtruncatemacro\cA{\cA+1)};
\pgfmathaddtocounter{cB}{1};
\node at (\x,1) { \cA };
\node at (\x,0) { \the\numexpr\value{cB} };
}
列印出這個
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
我需要
1 2 3 4 ...
是的,我可以在這個簡單的例子中僅使用\x
變數來做到這一點,但在我的真實圖表中我需要不規則地增加它們。所以我需要可以在循環內遞增而無需重置的變數。或者,我錯過了什麼並且它應該有效嗎?
答案1
要在循環中使用\foreach
,有更好的選擇:
\documentclass[tikz,border=2pt]{standalone}
\begin{document}
\begin{tikzpicture}
\foreach \i [count=\S from 5] in {1,...,5}
\node [draw, xshift=\i cm] {\S};
\end{tikzpicture}
\end{document}
count=\S from 5
這裡使用語法來\S
設定5
並1
在每次迭代中將其推進。另一種語法可能是evaluate=\i as \S using \i+4
,它將達到相同的結果。
更新
可以根據如下條件在循環內更改增量:
\newcounter{cA}
\setcounter{cA}{0}
\newcounter{cB}
\setcounter{cB}{0}
\begin{tikzpicture}
\foreach \x in {1,...,10}{
\addtocounter{cA}{1}
\ifnum\x<6\addtocounter{cB}{1}\else\addtocounter{cB}{2}\fi
\node at (\x,1) { \thecA };
\node at (\x,0) { \thecB };
}
\end{tikzpicture}
答案2
無需pgf
對計數器使用數學。您可以只使用\setcounter
,\stepcounter
或\addtocounter
。使用這些,計數器值在循環後保留\foreach
:
不確定我是否完全理解給出的意圖程式碼片段,但也可以輕鬆調整以使用 TeX 計數器(如下面的第二個 MWE 所示):
代碼:
\documentclass{article}
\usepackage{tikz}
\newcounter{foo}
\begin{document}
\setcounter{foo}{0}
After \verb|\setcounter|: foo=\arabic{foo}
\stepcounter{foo}
After \verb|\stepcounter|: foo=\arabic{foo}
\addtocounter{foo}{4}
After \verb|\addtocounter|: foo=\arabic{foo}
\foreach \x in {1,...,20} {%
\stepcounter{foo}%
}%
After \verb|\foreach|: foo=\arabic{foo}
\end{document}
代碼:
\documentclass{article}
\usepackage{tikz}
\newcounter{cA}
\newcounter{cB}
\begin{document}
\begin{tikzpicture}
\foreach \x in {1,...,10} {%
\stepcounter{cA};
\stepcounter{cB};
\node at (\x,1) { \the\value{cA} };
\node at (\x,0) { \the\value{cB} };
}
\end{tikzpicture}
\end{document}
答案3
它適用於 pgf 3.0.1a:
\documentclass{article}
\usepackage{pgf}
\pgfmathsetmacro\S{5}
\pgfmathsetmacro\S{\S + 1}
\begin{document}
\S
\end{document}
評論: