
我想得到這個:
我嘗試使用ifthenelse
insideforeach
但出現錯誤:Missing number, treated as zero. <to be read again> = l.9 }
。這裡esdd 說“\ifthenelse
是“正常”LaTeX 程式碼。因此您不能在 TikZ 路徑規範中使用此命令。”但是,我不知道如何解決這個問題。這是我的程式碼:
\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}
答案1
當然可以使用\ifthenelse
,但是
- 測試僅比較整數
- 它使用單一
=
- 當 TikZ 到達 1.6 時,它實際上將其視為 1.59998
使用整數,則:
\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}
答案2
另一種方法是將標準\ifnum
構造與\pgfmathparse
.請注意,由於 1.6 是浮點數,因此您必須提供容差。一個簡單的方法\pgfmathparse{\y == 1.6 ? int(1) : int(0)}
是行不通的。
這是完整的解決方案:
\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}
答案3
強制xintexpr
解決方案。這次我饒了你們\xintFor
,因為\foreach
太可敬了。
我不知道如何\foreach
先擴展其列表參數,因此我必須先使用TikZ
手冊中的設備並進行\mylist
定義。
這裡的方法適用於定點運算必須精確的更複雜的情況。
\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}