arrays - 在 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
解决方案
第一件事:不能将 bash 变量直接视为浮点值。数字 bash 值只是整数。
您可以使用其他工具来执行浮点计算。即您可以像在代码片段中那样使用“bc”。
您的问题很可能与 bash 解释的括号有关,而不是发送到“bc”。在将计算传递给 bc 之前,您必须首先将计算构建为字符串。
我会这样写:
echo "${assets[i]} - ( ${reported[i]} + ( ${affiliate[i]} * -1 ) + ${loans[i]} + ( ${credit[i]} - ${debit[i]} ))" | bc
推荐阅读
- rust - 为什么不能装箱
被用作需要实现 T 的关联类型? - azure - 仅使用 Azure AD 身份时,如何在新的 Azure API 管理开发人员门户中将用户添加到管理员组?
- amazon-elastic-beanstalk - WSGI 路径不适用于 Amazon Linux 2
- r - R粘贴时间差与单位(秒,分钟等)
- dialogflow-cx - Dialogflow CX - 使用 sys.person 给出奇怪的输出
- node.js - RxJS:使用 NestJS HttpService 对分页 API 进行并行 http 调用
- jquery - 在 jQuery 中使用箭头键移动表格的行
- elasticsearch - Elasticsearch - 搜索小于 min_gram 的词
- linux - Docker 容器 - 使用 xclip 提取文本
- amazon-web-services - AWS- 数据没有从 Lambda 保存到 DynamoDB