同じ変数を使用して変数を増やすにはどうすればよいでしょうか?

同じ変数を使用して変数を増やすにはどうすればよいでしょうか?

同じ変数から変数を増分するにはどうすればよいですか?

\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使用されています。別の構文は で、同じ結果が得られます。\S51evaluate=\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 カウンターを使用するように簡単に適応できます (以下の 2 番目の 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はパス コマンドではないため、その構文では閉じるセ​​ミコロンを認識しません。プリアンブルで追加のセミコロンがあるとエラーが発生します (欠落\begin{document})。

  • 結果として整数を取得したい場合は、次の\pgfmathtruncatemacro方法が役立ちます:

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

    \pgfmathtruncatemacro を使用した結果

関連情報