如何根據我們是否位於部分或小部分內來調整計數器

如何根據我們是否位於部分或小部分內來調整計數器

我想創建一個exercise可以在任何部分、小節等中使用的環境。

  • 在第 1 節中,第三個範例的標題應為例1.3, 但
  • 在第 1 節和第 2 小節中,第三個範例的標題應為例1.2.3

這個怎麼做?

在此輸入影像描述

\documentclass{article}
\usepackage{tcolorbox}

\newcounter{exercise}
\newenvironment{exercise}
{\par\smallskip\refstepcounter{exercise}\begin{tcolorbox}[title=Exercise \thesection.\thesubsection.\theexercise]\ignorespaces}
{\end{tcolorbox}\par\smallskip\ignorespacesafterend}

\begin{document}
\section{Polynomial}
In this section we will study expressions in the following form.
\[
a_0 x^n + a_1 x^{n-1} \cdots + a_n
\]
where \ldots
\begin{exercise}
Is $\frac{x-1}{2}$ a polynomial?
\tcblower
Yes. Because it can be rewritten as $x/2-1/2$.
\end{exercise}
\begin{exercise}
Is $0$ a polynomial?
\tcblower
Yes.
\end{exercise}
\subsection{Order}
The highest exponent in polynomial terms represents the order of  the polynomial.
\begin{exercise}
What is the order of $2x^3-3x^5+1$?
\tcblower
The highest exponent is 5 so the polynomial order is 5.
\end{exercise}
\end{document}

我做了以下操作,但是當我在小節時,輸出有雙小節。

\newcounter{exercise}
\newenvironment{exercise}
{\par\smallskip\refstepcounter{exercise}\begin{tcolorbox}[title=Exercise \thesection\ifnum\value{subsection}>0.\thesubsection\fi.\theexercise]\ignorespaces}
{\end{tcolorbox}\par\smallskip\ignorespacesafterend}

筆記:

歡迎提出最佳實踐建議,以使環境變得越來越複雜,例如可以透過標籤引用等...

答案1

在此輸入影像描述

您希望添加前綴,以便不僅僅在標題中\theexercise看到它。\ref

\documentclass{article}
\usepackage{tcolorbox}

\newcounter{exercise}[subsection]
\renewcommand\theexercise{%
\thesection.%
\ifnum\value{subsection}>0 \arabic{subsection}.\fi
\arabic{exercise}}

\newenvironment{exercise}
{\par\smallskip\refstepcounter{exercise}
\begin{tcolorbox}[title=Exercise \theexercise]\ignorespaces}
{\end{tcolorbox}\par\smallskip\ignorespacesafterend}

\begin{document}
\section{Polynomial}
In this section we will study expressions in the following form.
\[
a_0 x^n + a_1 x^{n-1} \cdots + a_n
\]
where \ldots
\begin{exercise}
Is $\frac{x-1}{2}$ a polynomial?
\tcblower
Yes. Because it can be rewritten as $x/2-1/2$.
\end{exercise}
\begin{exercise}
Is $0$ a polynomial?
\tcblower
Yes.
\end{exercise}
\subsection{Order}
The highest exponent in polynomial terms represents the order of  the polynomial.
\begin{exercise}
What is the order of $2x^3-3x^5+1$?
\tcblower
The highest exponent is 5 so the polynomial order is 5.
\end{exercise}
\end{document}

答案2

細化為大衛卡萊爾的解決方案,評論太長了:

\newcounter{exercise}[subsection]
\makeatletter
\@addtoreset{exercise}{section}
\makeatother

\renewcommand\theexercise{%
  \ifnum\value{subsection}>0 %
    \thesubsection
  \else
    \thesection
  \fi
  .\arabic{exercise}%
}

評論:

  • \newcounter{exercise}[subsection]只重置 new 的計數器\subsections,而不重置\section.\@addtoreset{exercise}{section}需要額外的。

  • 在裡面\theexercise我使用了,\thesubsection而不是\arabic{subsection},然後 中的變更\thesubsection會自動反映在 中\theexercise,例如,如果有人想要對小節使用與預設不同的編號樣式。

答案3

我認為您可以將分段計數器與零進行比較(例如使用 中的命令etoolbox)並使用它來決定如何組成數字。

相關內容