如何将浮点数分配到CMD一个变量? [英] How to assign a floating-point number to a variable in CMD?

查看:140
本文介绍了如何将浮点数分配到CMD一个变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我把它写成设置/p=7.34 它是只考虑7而不是7.34。我怎么能一个变量设置为一个浮点数?

When I write it as set /p=7.34 it is considering only 7 but not 7.34. How can I set a variable to a floating-point number?

推荐答案

好了,小评第一:可能的分配的任意浮点数在CMD的变量。问题是,当您要执行的算术运算的这种变量preserving小数。

Well, a small comment first: you may assign any floating-point number to a variable in CMD. The problem is when you want to perform arithmetic operations with such variable preserving decimal places.

我复制从以下答案<一个href=\"http://stackoverflow.com/questions/1503888/floating-point-division-in-a-dos-batch/28790263#28790263\">this帖子:

使用定点算术批处理很简单的操作。 定点是指你必须设置一些小数提前,并保持它整个的操作。两个固定点之间的数字加减法操作直接执行。乘法和除法运算需要一个辅助变量,我们可以称之为一,用1小数的正确数量(为0位)值。乘法之后,由一划分产品;分裂之前,乘以一的分红。在这里,它是:

Perform operations using fixed point arithmetic in Batch is simple. "Fixed point" means that you must set a number of decimals in advance and keep it throughout the operations. Add and subtract operations between two Fixed Point numbers are performed directly. Multiply and division operations requires an auxiliary variable, that we may call "one", with the value of 1 with the right number of decimals (as "0" digits). After multiply, divide the product by "one"; before division, multiply the dividend by "one". Here it is:

@echo off
setlocal EnableDelayedExpansion

set decimals=2

set /A one=1, decimalsP1=decimals+1
for /L %%i in (1,1,%decimals%) do set "one=!one!0"

:getNumber
set /P "numA=Enter a number with %decimals% decimals: "
if "!numA:~-%decimalsP1%,1!" equ "." goto numOK
echo The number must have a point and %decimals% decimals
goto getNumber

:numOK
set numB=2.54

set "fpA=%numA:.=%"
set "fpB=%numB:.=%"

set /A add=fpA+fpB, sub=fpA-fpB, mul=fpA*fpB/one, div=fpA*one/fpB

echo %numA% + %numB% = !add:~0,-%decimals%!.!add:~-%decimals%!
echo %numA% - %numB% = !sub:~0,-%decimals%!.!sub:~-%decimals%!
echo %numA% * %numB% = !mul:~0,-%decimals%!.!mul:~-%decimals%!
echo %numA% / %numB% = !div:~0,-%decimals%!.!div:~-%decimals%!

例如:

Enter a number with 2 decimals: 3.76
3.76 + 2.54 = 6.30
3.76 - 2.54 = 1.22
3.76 * 2.54 = 9.55
3.76 / 2.54 = 1.48

这篇关于如何将浮点数分配到CMD一个变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆