表形式環境のセルに合計を形成します。単純な算術演算ではマクロ展開またはインライン eval は可能ですか?

表形式環境のセルに合計を形成します。単純な算術演算ではマクロ展開またはインライン eval は可能ですか?

12 行ほどの明細行があり、それぞれに数値の整数コストが記された表形式の環境があります。最終行に合計を表示したいと思います。一定期間にわたって表の項目を何度も編集しましたが、そのたびに合計を再計算するという面倒な作業がありました。

単純な算術式をインライン評価する方法はありますか。たとえば、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}

ここに画像の説明を入力してください

関連情報