表格中 {>centering}p{width} 出现“放错 \noalign \hline”错误

表格中 {>centering}p{width} 出现“放错 \noalign \hline”错误

我不明白为什么将内容添加到最后一个单元格并结合居中选项会产生“放错 \noalign \hline”错误。以下是代码:

\documentclass[11pt,a4paper]{article}
\usepackage[utf8]{inputenc}
\usepackage{array}

\begin{document}
    \noindent This works:
    \begin{center}
        \begin{tabular}{|>{\centering}p{0.02\textwidth}|>{\centering}p{0.1\textwidth}|>{\centering}p{0.33\textwidth}|>{\centering}p{0.2\textwidth}|>{\centering}p{0.2\textwidth}|}
            \hline
            $n$ & $x_n$ & $f(x_n)$ & $f'(x_n)$ & \\
            \hline
        \end{tabular}
    \end{center}
    This too:
    \begin{center}
        \begin{tabular}{|p{0.02\textwidth}|p{0.1\textwidth}|p{0.33\textwidth}|p{0.2\textwidth}|p{0.2\textwidth}|}
            \hline
            $n$ & $x_n$ & $f(x_n)$ & $f'(x_n)$ & $x_{n+1}$ \\
            \hline
        \end{tabular}
    \end{center}
    But this gives a "misplaced \verb|\noalign| \verb|\hline|" error and an overfull \verb|\hbox|:
    \begin{center}
        \begin{tabular}{|>{\centering}p{0.02\textwidth}|>{\centering}p{0.1\textwidth}|>{\centering}p{0.33\textwidth}|>{\centering}p{0.2\textwidth}|>{\centering}p{0.2\textwidth}|}
            \hline
            $n$ & $x_n$ & $f(x_n)$ & $f'(x_n)$ & $x_{n+1}$ \\
            \hline
        \end{tabular}
    \end{center}
\end{document}

输出

答案1

根据 daleif 和 David Carlisle 的建议,添加以下内容\centering\arraybackslash可以解决问题:

\documentclass[11pt,a4paper]{article}
\usepackage[utf8]{inputenc}
\usepackage{array}

\begin{document}
    \begin{center}
        \begin{tabular}{|>{\centering}p{0.02\textwidth}|>{\centering}p{0.1\textwidth}|>{\centering}p{0.33\textwidth}|>{\centering}p{0.2\textwidth}|>{\centering}p{0.2\textwidth}|}
            \hline
            $n$ & $x_n$ & $f(x_n)$ & $f'(x_n)$ & $x_{n+1}$ \centering\arraybackslash\\ 
            \hline
        \end{tabular}
    \end{center}
\end{document}

以下是 David Carlisle 提出的另一个解决方案:

\documentclass[11pt,a4paper]{article}
\usepackage[utf8]{inputenc}
\usepackage{array}

\begin{document}
    \begin{center}
        \begin{tabular}{|>{\centering}p{0.02\textwidth}|>{\centering}p{0.1\textwidth}|>{\centering}p{0.33\textwidth}|>{\centering}p{0.2\textwidth}|>{\centering}p{0.2\textwidth}|}
            \hline
            $n$ & $x_n$ & $f(x_n)$ & $f'(x_n)$ & $x_{n+1}$ \tabularnewline 
            \hline
        \end{tabular}
    \end{center}
\end{document}

答案2

在下面的例子中,我A基于以下假设定义了一种新的列类型:所有单元格仅包含数学模式中的内容,并且表格的宽度应与文本宽度完全相同:

(红线表示边距)

在此处输入图片描述

\documentclass[11pt,a4paper]{article}

\usepackage{array}

\newcolumntype{A}[1]{>{\(}wc{\dimexpr #1\textwidth-2\tabcolsep-1.2\arrayrulewidth}<{\)}}

\begin{document}

\noindent
    \begin{tabular}{ | A{0.1} | A{0.1} | A{0.4} | A{0.2} | A{0.2} | }
            \hline
            n & x_n & f(x_n) & f'(x_n) & x_{n+1} \\ 
            \hline
    \end{tabular}

\end{document}

相关内容