“无效算术运算符"在 bash 中进行浮点运算时 [英] "Invalid Arithmetic Operator" when doing floating-point math in bash

查看:39
本文介绍了“无效算术运算符"在 bash 中进行浮点运算时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的脚本:

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

我收到错误Invalid Arithmetic Operator,(错误标记是.003")?

推荐答案

bash 不支持浮点运算.您需要使用像 bc 这样的外部实用程序.

bash does not support floating-point arithmetic. You need to use an external utility like 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))

这篇关于“无效算术运算符"在 bash 中进行浮点运算时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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