批处理-更高级的计算 [英] Batch- do more advanced calculations
问题描述
批量使用set /a
进行更高级的计算时遇到麻烦.小数将不起作用;例如,set /a 5/2
仅输出2
而不是2.5
.同样,批处理也无法处理大量计算.有没有办法只制作一个临时文件(如vbs)或调用另一个程序(如计算器)进行计算并将其返回到批处理文件中?
In batch, I have trouble doing more advanced calculations with set /a
. Decimals won't work; for example set /a 5/2
only outputs 2
instead of 2.5
. Also batch can't handle large calculations. Is there a way to just make a temp file (like vbs) or call on another program (like calculator) to do the calculation and return it back to the batch file?
推荐答案
下面的程序作为Batch-JScript混合脚本的示例,允许评估任何JScript表达式:
The program below as an example of a Batch-JScript hybrid script that allows to evaluate any JScript expression:
@if (@CodeSection == @Batch) @then
@echo off
rem Define an auxiliary variable to call JScript
set JScall=Cscript //nologo //E:JScript "%~F0"
for /F %%p in ('%JScall% Math.PI') do echo Intrinsic value of PI= %%p
for /F %%P in ('%JScall% 4*Math.atan(1^)') do echo Calculated value of PI= %%P
for /F %%S in ('%JScall% Math.sqrt(2^)') do echo Square Root of 2 = %%S
for /F %%t in ('%JScall% 1/3') do set oneThird=%%t
echo One third = %oneThird%
for /F %%o in ('%JScall% %oneThird%*3') do echo One third times 3 = %%o
goto :EOF
@end
// JScript section
WScript.Echo(eval(WScript.Arguments.Unnamed.Item(0)));
输出:
Intrinsic value of PI = 3.14159265358979
Calculated value of PI= 3.14159265358979
Square Root of 2 = 1.4142135623731
One third = 0.333333333333333
One third times 3 = 0.999999999999999
您可以在以下位置查看可用的JScript算术函数: http://msdn.microsoft.com/zh-CN/library/b272f386(v = vs.84).aspx
You may review the available JScript arithmetic functions at: http://msdn.microsoft.com/en-us/library/b272f386(v=vs.84).aspx
此方法允许将JScript代码保留在相同的.BAT文件中,并且比VBScript代码更简单,更快.
This method allows to keep the JScript code in the same .BAT file and is simpler and faster than the VBScript code.
这篇关于批处理-更高级的计算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!