FatTommy
FatTommy

Reputation: 327

How can I sum two numbers in Latex with my own command?

I have to sum two numbers (integers) in LaTeX. I also have to "print" the process of sum. So it would look like 5+2=7 in text. Any ideas? My code so far:

\newcommand{\Sum}
{\newcounter{cnt}
\setcountter{cnt}{1+1}
}

Upvotes: 11

Views: 17184

Answers (3)

Werner
Werner

Reputation: 15095

Perhaps a different syntax can be in order; instead of supplying each argument to calculate a sum, you can supply the operator with the operands. This allows you to be a little more flexible in terms of the input and also provide more functionality:

printed output

\documentclass{article}

\usepackage{xfp}

\NewDocumentCommand{\showcalculation}{o m}{$
  \IfValueTF{#1}
    {#1}{#2} = \fpeval{#2}
  $}

\begin{document}

\showcalculation{7+3}

\showcalculation{1+2-3+4}

\showcalculation[22 \div 7]{22 / 7}

\showcalculation[10 \times 3^{7 - 7}]{10 * 3 ^ (7 - 7)}

\end{document}

The optional argument for \showcalculation uses a LaTeX formatting for the printable calculation.

Upvotes: 6

FatTommy
FatTommy

Reputation: 327

I've managed to solve the problem.

\newcommand{\Sum} [2] {#1 + #2 = \the\numexpr #1 + #2 \relax \\}

And then I use my command as:

\Sum {7} {3}

Upvotes: 8

Phelype Oleinik
Phelype Oleinik

Reputation: 691

In LaTeX, first you have to define a counter with:

\newcounter{countername}

Then you can put a value in this counter with:

\setcounter{countername}{<value>}

where <value> is an integer. Or you can add one to this counter with:

\stepcounter{countername}

or you can add some arbitrary value to this counter with:

\addtocounter{countername}{<value>}

Then, to access this counter you use:

\value{countername}

so you can, for example, make calculations with this counter:

\setcounter{anothercounter}{%
  \numexpr\value{countername}+10\relax%
}

Then, when you need to print the value of this counter to the pdf file, you can you the mighty \the:

\the\value{countername}

or you can use one of these:

\arabic{countername}
\roman{countername}
\Roman{countername}
\alph{countername}
\Alph{countername}

Upvotes: 13

Related Questions