如何在Windows中使用SET命令进行浮点运算。/A代表算术运算,%VAR%打印的是VAR的内容而不是名称。
例如,当我执行以下操作时:
SET /A VAR="2.5+3.1"
ECHO %VAR%
pause
我遇到了“缺少运算符”的错误。 输出值(5.6)也应该转换为浮点数。
我仍在忙于学习基本语法。
谢谢,Snipe
如何在Windows中使用SET命令进行浮点运算。/A代表算术运算,%VAR%打印的是VAR的内容而不是名称。
例如,当我执行以下操作时:
SET /A VAR="2.5+3.1"
ECHO %VAR%
pause
REM Select two decimal digits for all operations
SET /A VAR=250+310
ECHO RESULT: %VAR:~0,-2%.%VAR:~-2%
rem Set "ONE" variable with two decimal places:
SET ONE=100
rem To multiply two FP numbers, divide the result by ONE:
SET /A MUL=A*B/ONE
rem To divide two FP numbers, multiply the first by ONE:
SET /A DIV=A*ONE/B
更多详细信息请参见此帖子。
你不能使用批处理来完成这个任务。它只能处理整数。 但是你可以使用Jscript或者Powershell:
>powershell 5.6+3.1
8.7
针对jscript,您需要创建一个额外的bat文件并调用它(例如jscalc.bat):
@if (@x)==(@y) @end /***** jscript comment ******
@echo off
cscript //E:JScript //nologo "%~f0" %*
exit /b 0
@if (@x)==(@y) @end ****** end comment *********/
WScript.Echo(eval(WScript.Arguments.Item(0)));
例子:
>jscalc.bat "4.1+4.3"
8.4
FOR /F
将结果设置为变量:>for /f "delims=" %# in ('powershell 5.6+3.1') do set result=%#
>set result=8.7
>for /f "delims=" %# in ('jscalc 5.6+3.1') do set result=%#
>set result=8.7
很可能您已经安装了PowerShell,但它并不是所有机器都可以使用(默认情况下不支持Vista、XP、2003),因此如果您没有安装,您需要使用jscalc.bat
。
另外,您也可以使用jscript.net(另一个jscript)。创建一个使用这个的.bat文件会更加冗长,并且会创建一个小的.exe文件,但这也是一种选项。以下是jsnetcalc.bat
:
@if (@X)==(@Y) @end /****** silent jscript comment ******
@echo off
::::::::::::::::::::::::::::::::::::
::: compile the script ::::
::::::::::::::::::::::::::::::::::::
setlocal
if exist "%~n0.exe" goto :skip_compilation
:: searching the latest installed .net framework
for /f "tokens=* delims=" %%v in ('dir /b /s /a:d /o:-n "%SystemRoot%\Microsoft.NET\Framework\v*"') do (
if exist "%%v\jsc.exe" (
rem :: the javascript.net compiler
set "jsc=%%~dpsnfxv\jsc.exe"
goto :break_loop
)
)
echo jsc.exe not found && exit /b 0
:break_loop
call %jsc% /nologo /out:"%~n0.exe" "%~f0"
::::::::::::::::::::::::::::::::::::
::: end of compilation ::::
::::::::::::::::::::::::::::::::::::
:skip_compilation
::
::::::::::
"%~n0.exe" %*
::::::::
::
endlocal
exit /b 0
****** end of jscript comment ******/
import System;
var arguments:String[] = Environment.GetCommandLineArgs();
Console.WriteLine( eval(arguments[1]) );
例子:
>jsnetcalc.bat 4.5+7.8
12.3
还有一种使用MSHTA的方法(在表达式中设置要计算的表达式):
@echo off
setlocal
:: Define simple macros to support JavaScript within batch
set "beginJS=mshta "javascript:close(new ActiveXObject('Scripting.FileSystemObject').GetStandardStream(1).Write(eval("
set "endJS=)));""
set "expression=8.5+3.5"
:: FOR /F does not need pipe
for /f %%N in (
'%beginJS% %expression% %endJS%'
) do set result=%%N
echo result=%result%
%VAR:~0,-2%.%VAR:~-2%
吗? - METALHEAD0,-2%获取整个字符串除了最后两个字符。 然后放置一个点(拼凑而成的小数点)。 然后%VAR:-2%获取字符串的最后两个字符。 因此,“100”将变为“1.00”,或“99999”将变为“999.99”。 - Adam Plocher