Calculating the sum of two variables in a batch script

[亡魂溺海] 提交于 2019-11-26 18:12:23

问题


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?


回答1:


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



回答2:


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!




回答3:


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



回答4:


@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



回答5:


You're looking for the '/a' property. Here:

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

'/a' is for math. You can't input letters into it. The default return value is 0. The output will be:

7
8



回答6:


@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



回答7:


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%


来源:https://stackoverflow.com/questions/10674974/calculating-the-sum-of-two-variables-in-a-batch-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!