计算批处理脚本中两个variables的总和

这是我第一次在堆栈溢出,所以请宽容这个问题。 我一直在尝试用批处理编程,并使用DOSbox在我的Linux机器上运行它们。

这是我一直在使用的代码:

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

其输出是:

 3+4 3+4+1 

我将如何添加两个variables而不是回显该string?

您需要使用set命令上的属性/a

例如,

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

这使您可以在set命令中使用算术expression式 ,而不是简单的连接。

您的代码将是:

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

并输出:

 7 8 

根据这个有用的运算符列表[一个运算符可以被认为是一个mathexpression式],您可以通过使用+ =运算符而不是+运算符来告诉批处理编译器,您正在操作variables而不是固定数字。

希望我帮助!

 @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 

您可以解决任何方程,包括添加此代码:

 @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 
 @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 

您正在寻找“/ a”属性。 这里:

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

'/ a'是math。 你不能input字母。 默认的返回值是0.输出将是:

 7 8 

这是我的

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