Как настроить счетчик в зависимости от того, находимся ли мы внутри раздела или подраздела

Как настроить счетчик в зависимости от того, находимся ли мы внутри раздела или подраздела

Я хочу создать 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) и использовать это, чтобы решить, как составить число.

Связанный контент