在 bash 中进行浮点数学运算时出现“无效的算术运算符”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35634255/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
"Invalid Arithmetic Operator" when doing floating-point math in bash
提问by John Smith
Here is my script:
这是我的脚本:
d1=0.003
d2=0.0008
d1d2=$((d1 + d2))
mean1=7
mean2=5
meandiff=$((mean1 - mean2))
echo $meandiff
echo $d1d2
But instead of getting my intended output of:
但不是得到我想要的输出:
0.0038
2
I am getting the error Invalid Arithmetic Operator, (error token is ".003")?
我收到错误 Invalid Arithmetic Operator, (error token is ".003")?
回答by chepner
bash
does not support floating-point arithmetic. You need to use an external utility like bc
.
bash
不支持浮点运算。您需要使用外部实用程序,例如bc
.
# Like everything else in shell, these are strings, not
# floating-point values
d1=0.003
d2=0.0008
# bc parses its input to perform math
d1d2=$(echo "$d1 + $d2" | bc)
# These, too, are strings (not integers)
mean1=7
mean2=5
# $((...)) is a built-in construct that can parse
# its contents as integers; valid identifiers
# are recursively resolved as variables.
meandiff=$((mean1 - mean2))
回答by MTSan
In case you do not need floating point precision, you may simply strip off the decimal part.
如果您不需要浮点精度,您可以简单地去除小数部分。
echo $var | cut -d "." -f 1 | cut -d "," -f 1
echo $var | cut -d "." -f 1 | cut -d "," -f 1
cuts the integer part of the value. The reason to use cut twice is to parse integer part in case a regional setting may use dots to separate decimals and some others may use commas.
削减值的整数部分。使用 cut 两次的原因是解析整数部分,以防区域设置可能使用点分隔小数而其他一些可能使用逗号。
回答by Karan Saxena
You can change the shell which you are using. If you are executing your script with bash shell bash scriptname.sh
try using ksh for your script execution. Bash doesn't support arithmetic operations that involve floating point numbers.
您可以更改正在使用的外壳。如果您使用 bash shell 执行脚本,请bash scriptname.sh
尝试使用 ksh 执行脚本。Bash 不支持涉及浮点数的算术运算。