表格環境中的循環

表格環境中的循環

我正在嘗試根據大小自動建立表格。 LaTeX 中有大量的循環命令,這使得很難找出哪一個是合適的。我嘗試了普通的 TeX 循環和包中的循環forlooppgfloop但沒有成功。

顯然,在環境中運行循環存在問題tabular。我還嘗試首先運行循環並將輸出字串保存到 a 中token,然後在tabular.這適用於某些情況。

這是一個最小的例子:首先,我想要產生什麼:

\begin{tabular}{|*{4}{c|}}
  1&2&3&4
\end{tabular}

在這裡,我對 TeX 循環進行了嘗試:

\newcounter{numofcol}\setcounter{numofcol}{4}
\newcounter{tmpcol}\setcounter{tmpcol}{1}

\begin{tabular}{|*{\thenumofcol}{c|}}
  \thetmpcol
  \loop
    \ifnum\value{tmpcol}<\value{numofcol}%
    \stepcounter{tmpcol}%
    &\thetmpcol
  \repeat
\end{tabular}

顯然,該&符號會導致循環中出現問題。如果我使用包forlooppgfloop.錯誤是

ERROR: Forbidden control sequence found while scanning use of \loop.

--- TeX said ---
<inserted text> 
                \par 
l.140     &
           \thetmpcol
--- HELP ---
No help available

因此我認為我可以將行的字串保存在tokenby中

\newcounter{numofcol}\setcounter{numofcol}{4}
\newcounter{tmpcol}\setcounter{tmpcol}{1}
\newtoks\tmprowcontent

\tmprowcontent={x}
\loop%
\ifnum\value{tmpcol}<\value{numofcol}%
  \stepcounter{tmpcol}%
  \tmprowcontent=\expandafter{\the\expandafter\tmprowcontent & x}%
\repeat

\begin{tabular}{|*{\thenumofcol}{c|}}
  \the\tmprowcontent
\end{tabular}

如果我不將該計數器包含在token.如果我替換x為當前計數器值,即

\newcounter{numofcol}\setcounter{numofcol}{4}
\newcounter{tmpcol}\setcounter{tmpcol}{1}
\newtoks\tmprowcontent

\tmprowcontent={\thetmpcol}
\loop%
\ifnum\value{tmpcol}<\value{numofcol}%
  \stepcounter{tmpcol}%
  \tmprowcontent=\expandafter{\the\tmprowcontent & \thetmpcol}%
\repeat

\begin{tabular}{|*{\thenumofcol}{c|}}
  \the\tmprowcontent
\end{tabular}

那麼每個條目都是計數器的最後一個值,即4在這種情況下。這是因為使用了\expandafter.但是,如果我不使用\expandafter,那麼 TeX 會告訴我記憶體不足。

因此,我的問題是我怎麼能做到這一點?

答案1

您可以簡單地迭代這些值,儘管您可能需要隱藏它,&這樣就不會太早看到它並在測試中結束表格單元格。

在此輸入影像描述

\documentclass{article}

\begin{document}

\newcounter{numofcol}\setcounter{numofcol}{4}
\newcounter{tmpcol}\setcounter{tmpcol}{0}

\newcommand\foo{%
  \stepcounter{tmpcol}%
  \thetmpcol
  \ifnum\value{tmpcol}<\value{numofcol}\hiddenamp\expandafter\foo\fi}
\newcommand\hiddenamp{&}

\begin{tabular}{|*{\thenumofcol}{c|}}
  \foo
\end{tabular}
\end{document}

相關內容