0

有没有办法使用 Mathjs 或其他一些 js lib 甚至 plainjs 来获得 sum-of-products 表达式的不同产品?Fe 将此表达式作为字符串给出:

7.30*7.40-2.10*1.30+8.10*(2.70+0.60+4.70)+0.30*0.60+ 1.60*0.70+2.95*2.65+6.00*5.80

该函数应该只执行乘法并返回不同乘积的不同总和。

结果应该是: 54.02 - 2.73 + 64.8 + 0.18...

它应该尊重父母。

4

1 回答 1

1

let str = "7.30*7.40-2.10*1.30+8.10*(2.70+0.60+4.70)+0.30*0.60+ 1.60*0.70+2.95*2.65+6.00*5.80"

let strArr = str.split("*")

let parsedParenthesis = strArr.map(expression => {
  if (!isNaN(expression))
    return expression
  let regex = /\(([^()]+)\)/g
  if (regex.test(expression)) {
    let matched = (expression.match(regex))[0]
    let exp = matched.split(/[\(\)]/)[1]
    let evaluatedExp = math.evaluate(exp) //if using mathjs
    expression = expression.replace(matched, evaluatedExp)
  }
  return expression
})
let finalString = parsedParenthesis.join("*")
let multiplyArr = finalString.match(/(\d+\.?\d*\*\d+\.?\d*)/g)
multiplyArr.map(exp => {
  let evaluatedExp = Math.round((math.evaluate(exp) + Number.EPSILON) * 100) / 100 //if using mathjs
  finalString = finalString.replace(exp, evaluatedExp)
})
console.log(finalString)
<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjs/7.0.2/math.js"></script>

于 2020-07-08T16:32:03.497 回答