首页 > 解决方案 > 在 shell 脚本中计算浮点数的算术计算

问题描述

我创建了 5 个仅包含浮点数(包含正数和负数)的数组。

以下是声明的数组:

我需要对数组执行以下公式,但它不起作用。
还有其他方法吗?

for((i =1 ; i <(#$assets[@]}; i++));do
echo ${assets[i]} - ( ${reported[i]} + ( ${affiliate[i]} * -1 ) + ${loans[i]} + (${credit[i]} - ${debit[i]})) | bc >> test.log

标签: arraysbashshellarithmetic-expressions

解决方案


第一件事:不能将 bash 变量直接视为浮点值。数字 bash 值只是整数。

您可以使用其他工具来执行浮点计算。即您可以像在代码片段中那样使用“bc”。

您的问题很可能与 bash 解释的括号有关,而不是发送到“bc”。在将计算传递给 bc 之前,您必须首先将计算构建为字符串。

我会这样写:

echo "${assets[i]} - ( ${reported[i]} + ( ${affiliate[i]} * -1 ) + ${loans[i]} + ( ${credit[i]} - ${debit[i]} ))" | bc

推荐阅读