如何使用相同的變數來增加變數?

如何使用相同的變數來增加變數?

如何從同一變數增加變數?

\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設定51在每次迭代中將其推進。另一種語法可能是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}

結果

評論:

  • \pgfmathsetmacro不是路徑命令,因此它的語法不知道結束分號。在序言中,附加分號會導致錯誤(Missing \begin{document})。

  • 如果你想得到一個整數作為結果,那麼\pgfmathtruncatemacro有幫助:

    \documentclass{article}
    \usepackage{pgf}
    \pgfmathsetmacro\S{5}
    \pgfmathtruncatemacro\S{\S + 1}
    
    \begin{document}
    \S
    \end{document}
    

    \pgfmathtruncatemacro 的結果

相關內容