在bash中创建高级计算器



我已经搜索过了,但除了一些基本的教程或帖子之外,找不到其他任何东西。

我想做的是一个更复杂的计算器(不使用bc(,它可以接受2个以上的参数。类似于:

./calc.sh 2 + 3 * 7 - 2 ^ 3

我的尝试如下:

  • 搜索运算符
  • 如果运算符为^或*,则计算并替换2^2+3*2-2为4+6-2
  • 将剩余部分添加到列表
  • 下一个循环检查:并进行计算,对+和-

这让我创作了这首";代码";但在运行它之后,我意识到它有一些主要问题,对我来说,更换删除项目并不是那么简单

#!/bin/bash
initial_data=($@)
result=0
sorted=()
for ((index=0; index <= ${#initial_data[@]}; index++)); do

if [ "${initial_data[index]}" == "^" ]; then
A=${initial_data[index-1]}
B=${initial_data[index+1]}
pow_value=$(($A**$B))
sorted+=$pow_value
elif [ "${initial_data[index]}" == "*" ]; then 
C=${initial_data[index-1]}
D=${initial_data[index+1]}
multi_value=`expr $C * $D`
sorted+=$multi_value
else
normal=${initial_data[index]}
sorted+=$normal
fi
done
echo ${sorted[@]}

然后我刮了这个,试了一些类似的东西

operators=('^' '*' '/' '+' '-')
data=("$@")
ops=()
for i in "${!data[@]}"; do
if (printf '%sn' "${operators[@]}" | grep -xq ${data[$i]}); then
ops+=("${data[$i-1]} ${data[$i]} ${data[$i+1]}")
fi  
done
declare -p ops 

这还没那么糟糕。它采用了运算符的顺序,但我没有考虑到calc中输入的奇数数量,它也看不到幂运算。

我有点不知所措。

您唯一需要计算的是幂的结果,其余的可以按如下所示进行:

echo $((2 + 3 * 7 - 2*2*2))

最新更新