如何使用 \ref 按照最初產生的方式列印計數器的值?

如何使用 \ref 按照最初產生的方式列印計數器的值?

我想用羅馬數字對表格中的行進行編號,然後當我交叉引用它們時,以相同的方式列印引用。

例如,

\documentclass{article}
\begin{document}
\newcounter{foo}
\newcommand{\rfoo}{\refstepcounter{foo}(\roman{foo})}

\begin{tabular}{r|l}

\hline

\rfoo\label{f1} & First line \\ \hline

\rfoo\label{f2} & Second line \\ \hline

\hline
\end{tabular}

\

The first line is \ref{f1}.  The second line is \ref{f2}.

\end{document}

給出

在此輸入影像描述

但我想要的是:

在此輸入影像描述

答案1

每個計數器都有一個叫做同胞宏\the...,說計數器foo就會有\thefoo。此\the...巨集預設使用阿拉伯數字輸出計數器值。

\thefoo也用於寫入檔案時的標籤.aux。如果(i)請求格式, ,則必須將其寫入.aux文件中並在\thefoo.

所以

\renewcommand{\thefoo}{(\roman{foo})}

是遊戲的名稱;-)

\documentclass{article}



\newcounter{foo}
\renewcommand{\thefoo}{(\roman{foo})}
\newcommand{\rfoo}{\refstepcounter{foo}\thefoo}

\begin{document} 
\begin{tabular}{r|l}

\hline

\rfoo\label{f1} & First line \\ \hline

\rfoo\label{f2} & Second line \\ \hline

\hline
\end{tabular}



The first line is \ref{f1}.  The second line is \ref{f2}.

\end{document}

在此輸入影像描述

這是自動行編號版本

\documentclass{article}


\usepackage{array}

\newcounter{foo}
\renewcommand{\thefoo}{(\roman{foo})}

% Define
\newcolumntype{R}{>{\refstepcounter{foo}\thefoo\arraybackslash}r}

\begin{document}

\begin{tabular}{R|l}

\hline

\label{f1} & First line \\ \hline

\label{f2} & Second line \\ \hline

 & ... line \\ \hline

\label{f4}  & ... line \\ \hline


\hline
\end{tabular}

\

The first line is \ref{f1}.  The second line is \ref{f2}.

And in line \ref{f4} you can see that

\end{document}

在此輸入影像描述

答案2

\label寫入\theX最後一個計數器X,因此相應地更新:

在此輸入影像描述

\documentclass{article}

\newcounter{foo}
\renewcommand{\thefoo}{(\roman{foo})}
\newcommand{\rfoo}{\refstepcounter{foo}\thefoo}

\begin{document}

\begin{tabular}{r|l}
  \hline
  \rfoo\label{f1} & First line \\
  \rfoo\label{f2} & Second line \\
  \hline
\end{tabular}

The first line is~\ref{f1}. The second line is~\ref{f2}.

\end{document}

作為參考,請參閱了解引用和標籤的工作原理

相關內容