我正在尝试创建一个具有自己的计数器的可引用环境,稍后我会在文本中引用它。我希望我的环境的计数器具有 Chapter.Number 样式。我已经能够使用此代码使其在新环境和新计数器中工作(问题末尾的 MWE):
\newcounter{code}[chapter]
\definecolor{bg}{rgb}{0.975,0.95,1.0}
\newenvironment{code}[3][hbp]
{\VerbatimEnvironment \refstepcounter{code}
\begin{listing}[#1]
\label{#3}
\textbf{Code~\arabic{chapter}.\arabic{code}} #2
\centering
\begin{minted}[bgcolor =bg, frame=lines,framesep=2mm,linenos]{julia}}
{\end{minted}\end{listing}}
(请注意, 的使用可能不正确\label
)
在我的文档中我使用如下环境:
It is possible to compute this histogram with a naive approach.
This is shown in Code~\ref{code1}.
A much smarter approach is instead presented in Code~\ref{code2}.
\begin{code}{Naive calculation}{code1}
function naivehist(data, ε)
Δ += sin(ε) # lalala
m = rand(1000,1000)
end
\end{code}
一切似乎都运行良好,除了引用代码块时:
我怀疑我\label
在自定义环境中对 的使用可能不正确。如何才能做到这一点,以便在使用时\ref{...}
我能正确获得数字2.1
而不是1
?
平均能量损失
\documentclass{book}
\usepackage[utf8]{inputenc}
\usepackage{minted} % for making code snippets
\usepackage{amsmath}
\begin{document}
\chapter{Title of chapter.}
\newcounter{code}[chapter]
\definecolor{bg}{rgb}{0.975,0.95,1.0}
\newenvironment{code}[3][hbp]
{\VerbatimEnvironment \refstepcounter{code}
\begin{listing}[#1]
\label{#3}
\textbf{Code~\arabic{chapter}.\arabic{code}} #2
\centering
\begin{minted}[bgcolor =bg, frame=lines,framesep=2mm,linenos]{julia}}
{\end{minted}\end{listing}}
the histogram equation:
\begin{equation}
\label{eq1}
p = \sum p_i + \int_0^1 \omega d\epsilon
\end{equation}
It is possible to compute this histogram with a naive approach. This is shown in Code~\ref{code1}.
\begin{code}{Naive, memory-inefficient calculation of eq.~\eqref{eq1}.}{code1}
function naivehist(data, a)
x += sin(a) # lalala
m = rand(1000,1000)
end
\end{code}
\end{document}
答案1
重新定义 \thecode 以提供正确的输出:
\documentclass{book}
\usepackage[utf8]{inputenc}
\usepackage{minted} % for making code snippets
\usepackage{amsmath}
\begin{document}
\chapter{Title of chapter.}
\newcounter{code}[chapter]
\renewcommand\thecode{\thechapter.\arabic{code}}
\definecolor{bg}{rgb}{0.975,0.95,1.0}
\newenvironment{code}[3][hbp]
{\VerbatimEnvironment \refstepcounter{code}\label{#3}%
\begin{listing}[#1]
\textbf{Code~\thecode} #2
\centering
\begin{minted}[bgcolor =bg, frame=lines,framesep=2mm,linenos]{julia}}
{\end{minted}\end{listing}}
the histogram equation:
\begin{equation}
\label{eq1}
p = \sum p_i + \int_0^1 \omega d\epsilon
\end{equation}
It is possible to compute this histogram with a naive approach. This is shown in Code~\ref{code1}.
\begin{code}{Naive, memory-inefficient calculation of eq.~\eqref{eq1}.}{code1}
function naivehist(data, a)
x += sin(a) # lalala
m = rand(1000,1000)
end
\end{code}
\end{document}