【问题标题】:Array arithmetic in bashbash中的数组算术
【发布时间】:2016-08-21 14:29:58
【问题描述】:

我在 bash 中有多个数组,例如 arrKey[]aarT[]P[],我想对这些数组进行算术运算。正如我检查的那样,数组工作正常,但是查找数组P[] 的算法是错误的。 有人可以帮我解决这个问题吗?

    #The format is C[0] = (A[0,0]*B[0]) + (A[0,1]*B[1]) 

这是我目前尝试过的代码。

    P[0]= $(({arrKey[0,0]} * {arrT[0]} ))+ $(({arrKey[0,1]} * {arrT[1]})) ))
    echo ${P[0]}

【问题讨论】:

标签: arrays bash shell math


【解决方案1】:

您的代码行有几个问题:

P[0]= $(({arrKey[0,0]} * {arrT[0]} ))+ $(({arrKey[0,1]} * {arrT[1]})) ))
  • =后面多了一个空格,擦掉吧。

    P[0]=$(({arrKey[0,0]} * {arrT[0]} ))+ $(({arrKey[0,1]} * {arrT[1]})) ))
    
  • 在算术展开式之外添加两个元素是不正确的。
    删除额外的括号:

    P[0]=$(({arrKey[0,0]} * {arrT[0]} + {arrKey[0,1]} * {arrT[1]}))
    
  • 要么使用$,要么从$(( … )) 内的变量中删除{…}

    P[0]=$(( arrKey[0,0] * arrT[0] + arrKey[0,1] * arrT[1] ))
    
  • 即使不是严格要求,引用您的扩展也是一个好主意:

    P[0]="$(( arrKey[0,0] * arrT[0] + arrKey[0,1] * arrT[1] ))"
    

另外,请确保 arrKey 已被声明为关联数组:

declare -A arrKey

确保预期的双索引 0,0 有效。

【讨论】:

    猜你喜欢
    • 2014-12-24
    • 2014-01-12
    • 2015-06-02
    • 2015-10-21
    • 1970-01-01
    • 2015-10-15
    • 2011-01-31
    • 1970-01-01
    • 2012-04-22
    相关资源
    最近更新 更多