[Tex/LaTex] Table reference not compiling correctly

cross-referencingtables

I'm hoping for some guidance on why LaTeX isn't properly referencing this table.

\begin{table}[ht] 
\caption*{Table 2 \\ Number and Percentage}\label{tab:table2} 
\centering
\begin{tabular}{rrrrrr}
\hline
 & \# & \# & \# & \% & \% \\ 
  \hline
  A  & 446 & 105 & 42 & 23.54 & 9.42 \\ 
  B  & 389 & 6 & 69 & 1.54 & 17.74 \\ 
  C  & 355 & 8 & 79 & 2.25 & 22.25 \\ 
  D  & 343 & 21 & 107 & 6.12 & 31.20 \\ 
  \hline
\end{tabular}
\end{table}

In Table~\ref{tab:table2} ...

I've tried compiling multiple times and moving the label inside the caption, but neither of those has worked; I still get "In Table ??" as output. Why might this be happening? Thanks for any help!

Best Answer

As @DavidCarlisle notes in the comments, \caption* does not update a counter, so there is nothing for \label to label.

The caption documentation says (p. 17):

The longtable package defines the command \caption* which typesets the caption without label and without entry in the list of tables. [. . .] The caption package offers this feature, too, so you can use this command now within every floating environment [emphasis added]

To achieve the format that you want (as you noted in the comments), you can just make use of caption's \captionsetup.

Also, I've taken the liberty of using booktabs in the following MWE. You might want to use this package in order to typeset nicer tables. See the documentation for some tips on typesetting tables. In brief, the package provides \toprule, \bottomrule, and \midrule, which are nicer than \hline.

\documentclass{article}

\usepackage{caption}
\captionsetup[table]{
    labelsep=newline,
    justification=centering
    }

\usepackage{booktabs} % for nicer looking tables

\begin{document}

\begin{table}[ht] 
\caption{Number and Percentage}\label{tab:table2} 
\centering
\begin{tabular}{rrrrrr}
\toprule
 & \# & \# & \# & \% & \% \\ 
  \midrule
  A  & 446 & 105 & 42 & 23.54 & 9.42 \\ 
  B  & 389 & 6 & 69 & 1.54 & 17.74 \\ 
  C  & 355 & 8 & 79 & 2.25 & 22.25 \\ 
  D  & 343 & 21 & 107 & 6.12 & 31.20 \\ 
  \bottomrule
\end{tabular}
\end{table}

In Table~\ref{tab:table2} ...

\end{document}

enter image description here

Related Question