將字串轉換為計數

將字串轉換為計數

我正在從 aux 檔案中讀取一個數字(作為文字),並且我想\ifnum對其進行數值測試 ( )。我可以使用\setcounterand \value,但我真的不想創建一個計數器只是為了做一個糟糕的測試。有沒有更簡單的方法?

使用 pgfmath 絕非想像中那麼簡單。

\documentclass{article}
\newcount\test
\newcounter{test}
\begin{document}

\def\temp{1}

\setcounter{test}{\temp}
\ifnum\value{test}>0 Yea!
\else Boo!
\fi

\test=\temp
\ifnum\test>0 Yea!
\else Boo!
\fi

\end{document}

回想起來,我的錯誤是顯而易見的。在這樣的表達中

\test=1

行尾終止添加數字和“1”到計數的轉換。但與

\test=\temp

行尾用於終止巨集名稱。我懷疑這最終的擴展實際上是

\test=1 Boo!

這是合法的,但為時已晚。最簡單的解決方案

\test=\temp\relax

用於\relax強製表達式完成。

答案1

正如我在評論中指出的,您可以放棄計數器。只需使用 the\def作為參數即可。如果您需要更複雜的計算,可以使用\numexpr,如我的第二個範例所示。

\documentclass{article}
\begin{document}

\def\temp{1}
\def\X{2}

\ifnum\temp>0 Yea!
\else Boo!
\fi

\ifnum\numexpr\temp-\X\relax>0 Yea!
\else Boo!
\fi

\end{document}

在此輸入影像描述


為了跟進 OP 關於混合代幣和計數器的難度的評論,我將發布適用於該混合的 MWE:

\documentclass{article}
\newcounter{mycount}
\setcounter{mycount}{0}
\begin{document}
\def\temp{1}
\ifnum\value{mycount}>\temp Yea!
\else Boo!
\fi
\end{document}

相關內容