创建一个计算器脚本 [英] Creating a calculator script

查看:123
本文介绍了创建一个计算器脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图与一个bash脚本的计算器。
 用户输入一个数字,选择他们是否愿意加,减,乘或除。然后用户输入一个第二数目,并且能够选择是否执行的总和,或加,减,乘或上一个循环再次分裂。

I am trying to make a calculator with a bash script. The user enters a number, chooses whether they wish to add, subtract, multiply or divide. Then the user enters a second number and is able to choose whether to do the sum, or add, subtract, multiply or divide again on a loop.

我现在不能架我解决这个正确的头

I cannot rack my head around this right now

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

这是我迄今所做的,但任何人都可以帮我解决如何环回计算器?

This is what I have done so far, but can anyone help me work out how to loop back on the calculator?

推荐答案

鲜为人知的shell内建命令选择是非常方便的这种菜单驱动程序:

The lesser-known shell builtin command select is handy for this kind of menu-driven program:

#!/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的特点和干:


If I was going to get fancy with bash v4 features and 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

这篇关于创建一个计算器脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆