如何提示用户输入两个数字,然后选择使用条件语句中的算术操作员在bash脚本中使用的算术运算符?
我正在尝试编程一个代码,其中提示用户输入2个数字,然后选择执行操作员。我试图运行此操作,但是如果语句不起作用,我不知道问题所在。
echo "Enter 1st number: "
read num1
echo "Enter 2nd number: "
read num2
echo "a. Add b. Subtract c. Multiply d. Divide"
echo "Enter Operator: "
read opr
if [[$opr==A]]
then
sum=$(($num1 + $num2))
echo "The sum is $sum."
elif [[$opr==B]]
then
diff=$(($num1 - $num2))
echo "The difference is $diff"
elif [[$opr==C]]
then
prod=$(($num1 * $num2))
echo "The product is $prod"
elif [[$opr==D]]
then
quot=$(($num1 / $num2))
echo "The quotient is $quot"
else
echo "Invalid. Please enter A, B, C, and D only."
fi
I am trying to program a code where a user is prompted to input 2 numbers and choose an operator to execute. I tried to run this but the if statements don't work and I don't know the problem.
echo "Enter 1st number: "
read num1
echo "Enter 2nd number: "
read num2
echo "a. Add b. Subtract c. Multiply d. Divide"
echo "Enter Operator: "
read opr
if [[$opr==A]]
then
sum=$(($num1 + $num2))
echo "The sum is $sum."
elif [[$opr==B]]
then
diff=$(($num1 - $num2))
echo "The difference is $diff"
elif [[$opr==C]]
then
prod=$(($num1 * $num2))
echo "The product is $prod"
elif [[$opr==D]]
then
quot=$(($num1 / $num2))
echo "The quotient is $quot"
else
echo "Invalid. Please enter A, B, C, and D only."
fi
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
中的错误[[
撇开,我建议使用case
语句:Error in
[[
aside, I would recommend using acase
statement instead:需要在所有
中放置在双方平方括号之间
如果语句:此外:bash对案例敏感,则 :
上面的语法将$ opr变量的值转换为大写,无论您输入什么。
You need to put spaces between double square brackets in all
if
statements:Moreover: bash is case sensitive, so if you want to match both uppercase and lowercase letters from your input request, you should use something like this:
That above syntax converts the value of $opr variable to uppercase, whatever you typed.
我建议这样做:
它更清洁,并取得了理想的结果。
I would suggest this:
It's a lot cleaner and achieves your desired result.