陣列:設定某些列的寬度

陣列:設定某些列的寬度

我有一個array(在數學模式下),我希望第一列比其餘列寬一點,其餘列的寬度應一致。如果我只是寫

\begin{array}{c|ccc}
10000 & 1 & 20 & 300
\end{array}

那麼第二、第三和第四列都有單獨的寬度,這是我想要避免的。理想情況下,我想將第一列的寬度設為 例如,2cm將其餘列的寬度設為1cm

有沒有辦法做到這一點?我想避免嵌套array環境。

答案1

我假設 (a) 第 2、3 和 4 列都應與任何一列中最寬的元素一樣寬 - 您提供的表中的“300” - 並且 (b)這些內容的內容應該居中。如果這種解釋是正確的,我建議您繼續定義一個新的列類型(C在下面的程式碼中呼叫),它滿足這些假設,並且預設將其內容置於數學模式。

我在程式碼中添加了垂直條,以便清楚地看出第 2、3 和 4 列確實具有相同的寬度。

在此輸入影像描述

\documentclass{article}
\newlength\mylen
\usepackage{array} % for "\newcolumntype" macro
\newcolumntype{C}{>{\hfil$}p{\mylen}<{$\hfil}} % centered, in math mode, fixed width
\begin{document}
\[
\settowidth\mylen{300} % choose widest element in columns 2--4
\begin{array}{|c|C|C|C|}
10000 &  1  &  20 & 300\\
1     & 101 & 555 & 888\\ 
\end{array}
\]
\end{document}

更新,2021 年 6 月:自從我發布這個答案以來已經過去了 4 年多的時間,該array軟體包已進行了重大更新。其中一項更新是引入了w列類型,上面的設定可以更簡潔地重寫如下:

\documentclass{article}
\newlength\mylen
\usepackage{array} % for 'w' column type
\begin{document}
\[
\settowidth\mylen{300} % choose widest element in columns 2--4
\begin{array}{| c | *{3}{wc{\mylen}|} }
10000 &  1  &  20 & 300\\
1     & 101 & 555 & 888
\end{array}
\]
\end{document}

答案2

一種可能性是dcolumn

\documentclass{article}
\usepackage{dcolumn,booktabs}

\begin{document}

\[
\begin{array}{r *{3}{D{.}{.}{3.-1}}}
\toprule
10000 &  1 & 20 & 300 \\
100   & 10 & 10 &  10 \\
\bottomrule
\end{array}
\]

\[
\begin{array}{r *{3}{D{.}{.}{3.-1}}}
\toprule
10000 & 100 & 200 & 300 \\
100   & 100 & 100 & 100 \\
\bottomrule
\end{array}
\]

\end{document}

第二個表顯示間距是相同的。列類型的參數D分別是輸入小數分隔符號、輸出小數分隔符號和數字格式;這裡的3.-1意思是「整數部分三位數字,沒有小數位。

在此輸入影像描述

答案3

\hphantom使第二列到第四列的列寬相等的解:

\documentclass{article}
\begin{document}
\[
  \begin{array}{c|ccc}
    10000 & \hphantom{00}1 & \hphantom{0}20 & 300
  \end{array}
\]
\end{document}

結果

列類型p也適用於array,例如:

\documentclass{article}
\usepackage{array}
\begin{document}
\[
  \begin{array}{>{\centering}p{2cm}|*{3}{>{\centering}p{1cm}}}
    10000 & 1 & 20 & 300
  \end{array}
\]
\end{document}

結果

或將列與包對齊siunitx

\documentclass{article}
\usepackage{siunitx}
\begin{document}
\[
  \begin{array}{S[table-format=5]|*{3}{S[table-format=3]}}
    10000 & 1 & 20 & 300
  \end{array}
\]
\end{document}

結果

相關內容