尝试重新格式化子节时 If/Else 语句不起作用

尝试重新格式化子节时 If/Else 语句不起作用

我希望我的 LaTeX 代码能够对章节和小节进行编号,例如(仅供参考:我使用的是articlenotchapterbook):

0 Introduction (section)
1 A (section)
1.01 A1 (subsection)
1.02 A2 (subsection)
...
1.10 A10
1.11 A11
2 B

However, this is spitting out:
0 Introduction (section)
1 A (section)
1.01 A1 (subsection)
1.02 A2 (subsection)
...
1.010 A10
1.011 A11
2 B

不知何故,我的 if/else 语句没有起作用。有人知道为什么吗?

代码如下:

\documentclass[a4paper, 12pt]{article}

\setcounter{section}{-1}
\renewcommand{\thesection}{Module \arabic{section}}


\ifnum\value{subsection}<10
    \renewcommand\thesubsection{\thesection.0\arabic{subsection}}
\else 
    \ifnum\value{subsection}<100
    \renewcommand\thesubsection{\thesection.\arabic{subsection}}
\fi
\fi
\begin{document}

\title{Notes}
\author{}
\date{}
\maketitle

\section{Introduction}

\section{A}

\subsection{A1}

\subsection{A2}

\subsection{A3}

\subsection{A4}

\subsection{A5}

\subsection{A6}

\subsection{A7}

\subsection{A8}

\subsection{A9}

\subsection{A10}

\subsection{A11}

\section{B}

\subsection{B1}

\subsection{B2}

\section{C}

\section{D}

\section{E}

\end{document}

答案1

您的值只会被评估一次,恰好在值为 0 的\ifnum时刻。subsection

您需要评估条件什么时候 \thesection扩展为:

\renewcommand{\thesection}{%
  \thesection.%
  \ifnum\value{subsection}<10
    0%
  \else
    \ifnum\value{subsection}<100
      0%
    \fi
  \fi
  \arabic{subsection}%
}

一个不同的解决方案xparse,可以轻松推广到任何(固定)填充:我们计算扩展中的项目数\arabic{subsection}(即数字的数量),并相应地用零填充,在本例中为三位数。

\usepackage{xparse}

\ExplSyntaxOn
\RenewExpandableDocumentCommand{\thesubsection}{}
 {
  \thesection.
  \prg_replicate:nn { 3 - \tl_count:f { \arabic{subsection} } } { 0 }
  \arabic{subsection}
 }
\cs_generate_variant:Nn \tl_count:n { f }
\ExplSyntaxOff

完整示例:

\documentclass[a4paper, 12pt]{article}
\usepackage{xparse}

\setcounter{section}{-1}
\renewcommand{\thesection}{Module \arabic{section}}

\ExplSyntaxOn
\RenewExpandableDocumentCommand{\thesubsection}{}
 {
  \thesection.
  \prg_replicate:nn { 3 - \tl_count:f { \arabic{subsection} } } { 0 }
  \arabic{subsection}
 }
\cs_generate_variant:Nn \tl_count:n { f }
\ExplSyntaxOff

\begin{document}

\title{Notes}
\author{}
\date{}
\maketitle

\section{Introduction}

\section{A}

\subsection{A1}

\subsection{A2}

\subsection{A3}

\subsection{A4}

\subsection{A5}

\subsection{A6}

\subsection{A7}

\subsection{A8}

\subsection{A9}

\subsection{A10}

\subsection{A11}

\setcounter{subsection}{99}

\subsection{A100}

\section{B}

\subsection{B1}

\subsection{B2}

\section{C}

\section{D}

\section{E}

\end{document}

在此处输入图片描述

答案2

\if条件属于宏定义\thesubsection

\renewcommand\thesubsection{\thesection.\ifnum\value{subsection}<10 0\fi\arabic{subsection}}

相关内容