在表格環境的儲存格中形成總計。巨集擴展或內聯評估可以用於簡單算術嗎?

在表格環境的儲存格中形成總計。巨集擴展或內聯評估可以用於簡單算術嗎?

我有一個表格環境,其中有大約十幾行逐項列出,每行都有一個數字整數成本。我想在最後一行顯示總計。在一段時間內,我多次編輯了表中的項目,每次都繁瑣地重新計算總數。

有沒有辦法對簡單的算術公式進行內聯求值,例如類似於 bash 的 $(()): 的東西,The total is $((12 + 34 + 23 + ... + 5))其中將顯示求值表達式,而不是字面方程式。我很樂意更改項目的行值,並更改方程式中的相應數字(我認為這裡不需要完整的電子表格表現力)。

我也不想添加預處理步驟來從模板生成表。表的大小還不能保證這一點。

我認為 tex 中必須有一種簡單的內建方法來顯示與來源文件內聯定義的計算結果。也許是透過濫用自訂計數器,或透過定義新的命名長度,向其添加單位,然後顯示其值?

試圖實現這樣的目標(偽代碼):

% initialize the current total to 0 before the table
{\thetotal = 0}

\begin{tabular}{@{}lp{4cm}r@{}} \toprule
  Store & Purpose & Items\\
  \midrule
  Safeway & for the salad   &    10 tomatoes  {\thetotal += 10} \\
  Whole Foods & for dessert &     4 muffins   {\thetotal += 4}  \\
  % ...
  % many more rows here.
  % in each row, \thetotal is incremented. This way, if I change
  % one line's value, I can change just that line and I don't need
  % to change anything else.
  % ...
  Home Depot & leftovers &     17 mouse traps {\thetotal += 17} \\
  \bottomrule
  % Lastly, show the value of the counter at that point in the document
  \multicolumn{2}{r}{Total} & \thetotal items
\end{tabular}

我希望最後一行的最後一列顯示文件中該點的運行計數,即Total 31在本例中。

答案1

由於僅涉及整數值,因此該\addtocounter命令應該足夠了。

我稍微更改了表格並添加了\additems自動執行計算的命令。最終的牌桌設計留給OP

\documentclass{article}

\usepackage{booktabs}
\usepackage{siunitx}
\newcounter{total}
\newcommand{\additem}[2]{%
  \num{#1} & #2 &   \addtocounter{total}{#1} \thetotal
}

\begin{document}

\begin{tabular}{@{}lp{4cm}rlr@{}} \toprule
  Store & Purpose & \multicolumn{3}{c}{Items} \tabularnewline
  \midrule
  Safeway & for the salad   &    \additem{10}{tomatoes} \tabularnewline
  Whole Foods & for dessert &    \additem{4}{muffins}   \tabularnewline
  Home Depot & leftovers &     \additem{17}{mouse traps} \tabularnewline
  \bottomrule
  \multicolumn{4}{r}{Total} & \thetotal\ items
\end{tabular}


\end{document}

在此輸入影像描述

另一個沒有運行總和的版本

\documentclass{article}

\usepackage{booktabs}
\usepackage{siunitx}
\newcounter{total}
\newcommand{\additem}[2]{%
  \num{#1} & #2    \addtocounter{total}{#1} 
}

\begin{document}

\begin{tabular}{@{}lp{4cm}rl@{}} \toprule
  Store & Purpose & \multicolumn{2}{c}{Items} \tabularnewline
  \midrule
  Safeway & for the salad   &    \additem{10}{tomatoes} \tabularnewline
  Whole Foods & for dessert &    \additem{4}{muffins}   \tabularnewline
  Home Depot & leftovers &     \additem{17}{mouse traps} \tabularnewline
  \bottomrule
  \multicolumn{2}{r}{Total} & \thetotal & %items
\end{tabular}


\end{document}

在此輸入影像描述

相關內容