Calculating the sum of two variables in a batch script

Batch FileVariablesDosbox

Batch File Problem Overview


This is my first time on Stack Overflow so please be lenient with this question. I have been experimenting with programming with batch and using DOSbox to run them on my linux machine.

Here is the code I have been using:

@echo off
set a=3
set b=4
set c=%a%+%b%
echo %c%
set d=%c%+1
echo %d%

The output of that is:

3+4
3+4+1

How would I add the two variables instead of echoing that string?

Batch File Solutions


Solution 1 - Batch File

You need to use the property /a on the set command.

For example,

set /a "c=%a%+%b%"

This allows you to use arithmetic expressions in the set command, rather than simple concatenation.

Your code would then be:

@set a=3
@set b=4
@set /a "c=%a%+%b%"
echo %c%
@set /a "d=%c%+1"
echo %d%

and would output:

7
8

Solution 2 - Batch File

According to this helpful list of operators [an operator can be thought of as a mathematical expression] found here, you can tell the batch compiler that you are manipulating variables instead of fixed numbers by using the += operator instead of the + operator.

Hope I Helped!

Solution 3 - Batch File

@ECHO OFF
TITLE Addition
ECHO Type the first number you wish to add:
SET /P Num1Add=
ECHO Type the second number you want to add to the first number:
SET /P Num2Add=
ECHO.
SET /A Ans=%Num1Add%+%Num2Add%
ECHO The result is: %Ans%
ECHO.
ECHO Press any key to exit.
PAUSE>NUL

Solution 4 - Batch File

You can solve any equation including adding with this code:

@echo off

title Richie's Calculator 3.0

:main

echo Welcome to Richie's Calculator 3.0

echo Press any key to begin calculating...

pause>nul

echo Enter An Equation

echo Example: 1+1

set /p 

set /a sum=%equation%

echo.

echo The Answer Is:

echo %sum%

echo.

echo Press any key to return to the main menu

pause>nul

cls

goto main

Solution 5 - Batch File

@ECHO OFF
ECHO Welcome to my calculator!
ECHO What is the number you want to insert to find the sum?
SET /P Num1=
ECHO What is the second number? 
SET /P Num2=
SET /A Ans=%Num1%+%Num2%
ECHO The sum is: %Ans%
PAUSE>NUL

Solution 6 - Batch File

here is mine

echo Math+ 
ECHO First num:
 SET /P a= 
ECHO Second num:
 SET /P b=
 set /a s=%a%+%b% 
echo Result: %s%

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionswarajdView Question on Stackoverflow
Solution 1 - Batch FilestaticbeastView Answer on Stackoverflow
Solution 2 - Batch FilelolzeryestView Answer on Stackoverflow
Solution 3 - Batch FileLukeView Answer on Stackoverflow
Solution 4 - Batch FileRichieView Answer on Stackoverflow
Solution 5 - Batch FileTamil selvanView Answer on Stackoverflow
Solution 6 - Batch FileKiko TemelkView Answer on Stackoverflow