if 語句
在 latex 中,無論條件是否為真,我們都可以使用內建命令來執行程式碼。
比較兩個整數: \ifnum\value{num}>n {A} \else {B}\fi
此程式碼執行 A 如果 num> n else B.我們可以用<和=替換>。
如果數字是奇數: \ifodd\value{num} {A}\else {B}\fi
如果 num 是奇數,那麼它執行 A else B.
如果條件: \ifthenelse{condition}{A}{B}
我們必須載入 ifthen 包才能使用此命令。如果條件為真則執行 A else B.
用\( \),\AND,\OR,\NOT 創造複雜的條件是可能的。
例如: \ifthenelse{\(\NOT 4<2 \OR 4>11\)\AND\isodd{4}}{A}{B}
這段程式碼在頁面上寫下 B。\NOT 4<2 是真的,4>11 是假的。如果我們用 OR 連線 false 和 true 語句,那麼結果為 true。所以\(\NOT 4<2 \OR 4>11\) 是真的。\isodd{4} 是假的,因為 4 是偶數。與 AND 連線的 false 和 true 語句為 false,因此輸出為 B.
示例程式碼:
\documentclass{article}
\usepackage{ifthen}
\begin{document}
    \newcounter{num}
    \setcounter{num}{10}
    If num$>$100 then the next sentence will be "Num is large." else "Num is small."
    Num is \ifnum \value{num}>100 {large} \else {small}.
    If num is odd then the next sentence will begin with "Odd" if not then with "Even"
    \ifodd \value{num} {Odd} \else {Even} numbers are cool.
    If (num$>$3 and (1$<$0 or num$=$10)) is true then the next sentence will be "True." else "False."
    \ifthenelse{\value{num}>3\AND\(1<0 \OR \value{num}=10\)}{True.}{False.}
\end{document}
