Math on batch (win)

橙三吉。 提交于 2019-11-29 01:27:38
Kevin

The set command supports some limited calculation. In your case, you want: set /a result=(100*x)/y

Run set /? to see full documentation on what is supported. The /a switch does automatic variable substitution, so you can use x instead of %x%.

@echo off

set x=42
set y=5

set /a z = 100 * x / y

echo %z%

The set /a command allows you to assign the result of a mathematical expression to a variable (at that, the %'s around variable names in these expressions aren't required). See set /? for the list of supported operators and details.

Note that Windows batch files don't support floating-point arithmetic, so if an expression result is a fractional number, only the integer part will be counted. For example, 3/2 evaluates as 1 and 2/3 as 0.

DON'T do maths in batch. If you are doing percentage, you might have decimals and batch doesn't support decimals.(floating). Use vbscript or something better.

save the below as caculate.vbs

Set objFS=CreateObject("Scripting.FileSystemObject")
Set objArgs = WScript.Arguments
x = objArgs(0)
y = objArgs(1)
WScript.Echo ( x + 1 ) * 100  / y

and on command line

c:\test> cscript //nologo calculate.vbs 4 5
steven
  • set /a (any arithmatic)
  • set /a 2+2 adding
  • set /a 2-2 subtracting
  • set /a 2*2 multiplying
  • set /a 2/2 deviding
  • set /a 2^2 exponet

use brackets and parentheses to show the properties of the equations for ex. 2(2+2)=8 Shows distributive property.

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