gpt4 book ai didi

bash - 创建计算器脚本

转载 作者:行者123 更新时间:2023-11-29 09:17:15 24 4
gpt4 key购买 nike

我正在尝试用 bash 脚本制作一个计算器。 用户输入一个数字,选择他们是否希望加、减、乘或除。然后用户输入第二个数字,然后可以选择是否进行加法、减法、乘法或除法循环。

我现在不能绞尽脑汁解决这个问题

echo Please enter a number
read number

echo What operation would you like to perform: 1: Add, 2: Subtract, 3: Multiple, 4: Divide
read operation

case $operation in
1) math='+';;
2) math='-';;
3) math='*';;
4) math='/';;
*) math='not an option, please select again';;
esac
echo "$number $math"


echo Please enter a number
read number2

echo What operation would you like to perform: 1: Add, 2: Subtract, 3: Multiple, 4: Divide, 5: Equals
read operation2
case $operation2 in
1)math2='Add';;
2)math2='Subtract';;
3)math2='Multiply';;
4)math2='Divide';;
5)math2='Equals';;
*)math2='not an option, please select again';;
esac
echo You have selected $math2

exit 0

这是我到目前为止所做的,但是谁能帮我弄清楚如何在计算器上循环返回?

最佳答案

鲜为人知的 shell 内置命令 select 对这种菜单驱动程序很方便:

#!/bin/bash
while true; do
read -p "what's the first number? " n1
read -p "what's the second number? " n2
PS3="what's the operation? "
select ans in add subtract multiply divide; do
case $ans in
add) op='+' ; break ;;
subtract) op='-' ; break ;;
multiply) op='*' ; break ;;
divide) op='/' ; break ;;
*) echo "invalid response" ;;
esac
done
ans=$(echo "$n1 $op $n2" | bc -l)
printf "%s %s %s = %s\n\n" "$n1" "$op" "$n2" "$ans"
done

示例输出

what's the first number? 5
what's the second number? 4
1) add
2) subtract
3) multiply
4) divide
what's the operation? /
invalid response
what's the operation? 4
5 / 4 = 1.25000000000000000000

如果我想看中 bash v4 的特性和 DRY:

#!/bin/bash

PS3="what's the operation? "
declare -A op=([add]='+' [subtract]='-' [multiply]='*' [divide]='/')

while true; do
read -p "what's the first number? " n1
read -p "what's the second number? " n2
select ans in "${!op[@]}"; do
for key in "${!op[@]}"; do
[[ $REPLY == $key ]] && ans=$REPLY
[[ $ans == $key ]] && break 2
done
echo "invalid response"
done
formula="$n1 ${op[$ans]} $n2"
printf "%s = %s\n\n" "$formula" "$(bc -l <<< "$formula")"
done

关于bash - 创建计算器脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14350556/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com