TikZ 內的 ifthenelse:不工作

TikZ 內的 ifthenelse:不工作

我想得到這個:

在此輸入影像描述

我嘗試使用ifthenelseinsideforeach但出現錯誤: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,但是

  1. 測試僅比較整數
  2. 它使用單一=
  3. 當 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}

相關內容