
동일한 변수에서 변수를 어떻게 증가시킬 수 있습니까?
\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}
비고: