[Tex/LaTex] Table with fixed width centering won’t compile

tables

All, I don't think I've ever been this stuck. The following compiles. But if I uncomment the commented line, it does not compile. What am I doing wrong?

\documentclass[11pt]{article}
\usepackage{amsmath}
\usepackage{booktabs}
\usepackage{array}

\begin{document}

\begin{center}
\begin{tabular}{*{4}{>{\centering}p{2cm} |}}\toprule
%$x$ & $p$ & $xp$ & $x^2p$ \\\midrule
2 & 0.1 & &\\
3 & 0.2 & &\\
4 & 0.2 & &\\
5 & & &\\\midrule
$\sum x=$ & $\sum p=$ & $\sum xp=$ & $\sum x^2p=$ 
\end{tabular}
\end{center}

\end{document}

Best Answer

You need to use >{\centering\arraybackslash} since \centering redefines \\ (I removed the vertical lines since their use won't produce noce results, more if booktabs' features are in use):

\documentclass[11pt]{article}
\usepackage{amsmath}
\usepackage{booktabs}
\usepackage{array}

\begin{document}

\begin{center}
\begin{tabular}{*{4}{>{\centering\arraybackslash}p{2cm} }}\toprule
$x$ & $p$ & $xp$ & $x^2p$ \\\midrule
2 & 0.1 & &\\
3 & 0.2 & &\\
4 & 0.2 & &\\
5 & & &\\\midrule
$\sum x=$ & $\sum p=$ & $\sum xp=$ & $\sum x^2p=$ 
\end{tabular}
\end{center}

\end{document}

enter image description here

Another option is to use \tabularnewline instead of \\:

\documentclass[11pt]{article}
\usepackage{amsmath}
\usepackage{booktabs}
\usepackage{array}

\begin{document}

\begin{center}
\begin{tabular}{*{4}{>{\centering}p{2cm} }}\toprule
$x$ & $p$ & $xp$ & $x^2p$ \tabularnewline\midrule
2 & 0.1 & &\tabularnewline
3 & 0.2 & &\tabularnewline
4 & 0.2 & &\tabularnewline
5 & & &\tabularnewline\midrule
$\sum x=$ & $\sum p=$ & $\sum xp=$ & $\sum x^2p=$ 
\end{tabular}
\end{center}

\end{document}
Related Question