批处理脚本中的小数

4
echo off
cls

mode con: cols=55 lines=15

:MAIN
color 07
cls

set /p num1="Specify first number: "
cls
set /p num2="Specify second number: "
cls

set /a num3=%num1%*%num2%

echo %num3%
pause

如果num1 = 30,num2 = 0.10,那么它只会显示0而不是0.3,那么我该怎么做才能显示小数呢?如果需要,如何显示出5位小数?

1
我尝试了你的代码,甚至用SET /A num3=10*0.3替换了整个提示,但它产生了一个错误“缺少运算符”。SET命令的帮助文档中说:“数字值是十进制数,除非以0x为前缀表示十六进制数,以0表示八进制数。”所以我认为它只支持整数? - miltonb
http://www.robvanderwoude.com/battech_math.php - Endoro
@miltonb 我认为在那种意义上,“decimal”表示十进制编号系统--所以是的,它似乎只涵盖整数。 :( - BrainSlugs83
可能是SET命令 - 浮点数?的重复问题。 - phuclv
2个回答


1
::turn all strings with decimals to integers to perform arithmetic ops
::does not error check for non-numerics or non-numeric formatting
::I check beforehand or it's left as an exercise for the reader
set mynum=12.34
call:str2dec num pos %mynum%
echo str2dec num %num% , pos %pos% for %mynum%
set mynum=12.3
call:str2dec num pos %mynum%
echo str2dec num %num% , pos %pos% for %mynum%
set mynum=12.
call:str2dec num pos %mynum%
echo str2dec num %num% , pos %pos% for %mynum%
set mynum=12
call:str2dec num pos %mynum%
echo str2dec num %num% , pos %pos% for %mynum%
set mynum=.34
call:str2dec num pos %mynum%
echo str2dec num %num% , pos %pos% for %mynum%
GOTO:EOF
:Str2Dec
::Str2Dec(retVal,decPlaces,strIn)
::returns the integer to %1 of strIn, %3, shifted %2 places to the left
::e.g. Str2Dec num pos 12.34 returns num=1234 pos=2
 SET #=%3
 SET lengthInput=0
 SET decpoint=
 SET /A integerVal=0
 SET /A shifted=0
 :lenStr2Dec
 IF DEFINED # (SET #=%#:~1%&SET /A lengthInput+=1&GOTO:lenStr2Dec)
 IF !lengthInput! LSS 2 SET /A integerVal=%3&GOTO:xStr2Dec
 SET numString=%3
 FOR /L %%x IN (1,1,!lengthInput!) DO (
  SET /A startCharIndex=%%x-1
  CALL SET nextChar=%%numString:~!startCharIndex!,1%%
  IF "!nextChar!" == "." (
    SET decpoint=1
  ) ELSE (
    IF DEFINED decpoint SET /A shifted+=1
    SET /A nextNum=!nextChar!
    SET /A integerVal*=10
    SET /A integerVal+=!nextNum!
  )
 )
 :xStr2Dec
 SET "%~1=!integerVal!"
 SET "%~2=!shifted!"
GOTO:EOF

2
请添加一个描述,说明这如何解决用户的问题。另外,请阅读如何回答 - Roman Marusyk

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接