
Me gustaría conseguir esto:
Intenté usarlo ifthenelse
dentro foreach
pero aparece un error: Missing number, treated as zero. <to be read again> = l.9 }
.Aquíesdd dice " \ifthenelse
es código LaTeX" normal ". Por lo tanto, no puede utilizar este comando dentro de una especificación de ruta TikZ". Sin embargo, no sé cómo solucionar este problema. Aquí está mi código:
\documentclass[border=0.2cm]{standalone}
\usepackage{tikz}
\usepackage{ifthen}
\begin{document}
\begin{tikzpicture}
\foreach \y in {0,0.2,0.4,...,1.6}{
\ifthenelse{\y==1.6}{\draw [thin,-latex] (-0.8,1.6) -- (-0.3,1.6) node [above,midway] {U};}{\draw [thin,-latex] (-0.8,\y) -- (-0.3,\y);}
}
\end{tikzpicture}
\end{document}
Respuesta1
Seguramente puedes usar \ifthenelse
, pero
- la prueba compara solo números enteros
- utiliza un solo
=
- cuando TikZ llega a 1.6, en realidad lo ve como 1.59998
Utilice números enteros, entonces:
\documentclass[border=0.2cm]{standalone}
\usepackage{tikz}
\usepackage{ifthen}
\begin{document}
\begin{tikzpicture}
\foreach \y in {0,2,4,...,16}{
\ifthenelse{\y = 16}
{\draw [thin,-latex] (-0.8,1.6) -- (-0.3,1.6) node [above,midway] {U}}
{\draw [thin,-latex] (-0.8,\y/10) -- (-0.3,\y/10)}
;
}
\end{tikzpicture}
\end{document}
Respuesta2
Un enfoque alternativo sería la \ifnum
construcción estándar combinada con \pgfmathparse
. Tenga en cuenta que, dado que 1.6 es flotante, debe proporcionar una tolerancia. Un simple \pgfmathparse{\y == 1.6 ? int(1) : int(0)}
no funcionaría.
Aquí está la solución completa:
\documentclass[border=0.2cm]{standalone}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
\foreach \y in {0,0.2,0.4,...,1.6}{
\pgfmathparse{abs(\y - 1.6) < 0.001 ? int(1) : int(0)}
\ifnum\pgfmathresult=1
\draw [thin,-latex] (-0.8,\y) -- (-0.3,\y) node [above,midway] {U};
\else
\draw [thin,-latex] (-0.8,\y) -- (-0.3,\y);
\fi
}
\end{tikzpicture}
\end{document}
Respuesta3
La xintexpr
solución obligatoria. Esta vez les ahorro el \xintFor
, ya que \foreach
es demasiado venerable.
No sé cómo decirle \foreach
que primero se expanda su argumento de lista, por lo que primero tengo que recurrir al dispositivo del TikZ
manual con una \mylist
definición.
El método aquí es para situaciones más complicadas donde las operaciones de punto fijo deben ser exactas.
\documentclass[border=0.2cm]{standalone}
\usepackage{tikz}
\usepackage{xintexpr}
\begin{document}
\begin{tikzpicture}
\edef\mylist{\xinttheiexpr [1] 0..[+0.2]..1.6\relax}%
% (The [1] is to tell it to use fixed point notation
% with one digit after decimal mark, and this expands to
% 0, 0.2, 0.4, 0.6, 0.8, 1.0, 1.2, 1.4, 1.6 )
%
\foreach \y in \mylist
{%
\xintifboolexpr{\y = 1.6}
{\draw [thin,-latex] (-0.8,1.6) -- (-0.3,1.6) node [above,midway] {U}}
{\draw [thin,-latex] (-0.8,\y) -- (-0.3,\y)}
;
}
\end{tikzpicture}
\end{document}