
我有一個小的環境來列舉問題陳述。有時,我希望標籤不是數字,而是一些字串。在這種情況下,我不希望計數器增加。
% question environment
\newcounter{QuestionCounter}
\stepcounter{QuestionCounter}
\newenvironment{question}[1][\arabic{QuestionCounter}] {
\vspace*{0.5\baselineskip}
\noindent\textbf{Question #1. }\ignorespaces
\ifdefstrequal{#1}{\value{QuestionCounter}}
{\stepcounter{QuestionCounter}}
{}}{}
這裡涉及if-statement
的是,
\ifdefstrequal{#1}{\value{QuestionCounter}}
{\stepcounter{QuestionCounter}}
{}
如何比較參數的值(擴展?)#1
和計數器的值\value{QuestionCounter}
?我嘗試過,\ifdefstrequal{\value{#1}}{\value{QuestionCounter}}
因為我認為\ifdefstrequal
前兩個參數必須是巨集。
謝謝!
答案1
不,這是錯誤的用法。並且您需要進行完全擴展的測試。
我會用不同的方式來做:如果可選參數遺失(或為空),計數器被步進並用於對問題進行編號。
\documentclass{article}
\newcounter{QuestionCounter}
\newenvironment{question}[1][]
{%
\par\addvspace{0.5\baselineskip}%
\if\relax\detokenize{#1}\relax
\stepcounter{QuestionCounter}%
\thisquestion{\arabic{QuestionCounter}}%
\else
\thisquestion{#1}%
\fi
}{%
\par\addvspace{0.5\baselineskip}%
}
\newcommand{\thisquestion}[1]{%
\noindent\textbf{Question #1. }\ignorespaces
}
\begin{document}
\begin{question}
Is this a numbered question?
\end{question}
\begin{question}[foo]
Is this a numbered question?
\end{question}
\begin{question}
Is this a numbered question?
\end{question}
\end{document}