【问题标题】:Making a calculator that can loop - Bash [closed]制作一个可以循环的计算器 - Bash [关闭]
【发布时间】:2013-01-17 14:27:17
【问题描述】:

我正在尝试制作一个计算器。用户输入数字 1,选择并操作,输入数字 2,然后选择另一个操作或显示答案。

例如。 1 + 1 = 或者 1 + 1 + 2 + 1 =

这两个都应该是可能的。

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

exit 0

这是我到目前为止所写的,但我不知道如何让用户选择“等于”或循环返回以进入另一个操作。有什么想法可以在这里对我的代码做些什么吗?我整天都被困在这上面。

  • 我不希望用户自己输入方程式,我希望他们从列表中进行选择。

【问题讨论】:

  • 这个脚本对我根本不起作用。您是否复制/粘贴了正确的版本?
  • read -p "第一个数是多少?" n1 PS3="操作是什么?" select ans in add-sub-multiply-di-equals; do case $ans in add) op='+' ;休息 ;;减去) op='-' ;休息 ;;乘) op='*' ;休息 ;;除)op='/';休息 ;;等于) op= *) echo "无效响应" ;; esac done read -p "第二个数字是多少?" n2 ans=$(echo "$n1 $op $n2" | bc -l) printf "%s %s %s = %s\n\n" "$n1 " "$op" "$n2" "$ans" 退出 0
  • 是的@svnpenn 是正确的重复...

标签: linux bash shell unix


【解决方案1】:

基本上,您必须在该代码周围放置一个循环,以便它读取一个数字然后重复选择一个操作。建立公式。当用户选择“等于”时,跳出外循环并计算公式。在伪代码中:

formula=""
while true; do
  get a number
  formula+="$number"
  select an operation
    case $op in
    ...
    equals) break 2 ;; # need to break out of 2 levels, the select and the while
    esac
  done
  formula+="$op"
done
ans=$(bc -l <<< "$formula")
printf "%s = %s\n" "$formula" "$ans"

【讨论】:

    【解决方案2】:

    我会让用户一次性输入整个方程式。例如

    read -p "enter equation" equate
    ans=$(bc -l <<< "${equate%%=*})"
    echo ${equate%%=*} = $ans
    

    在一个 = 之后的任何事物的 %%=* 等价变量条中可能已被放入。

    【讨论】:

    • 我会使用这种方法,但是我想限制他们使用大小写能够输入的内容。
    【解决方案3】:
    #!/bin/bash
    
    read -p "what's the first number? " n1
    PS3="what's the operation? "
    select ans in add subtract multiply divide equals; do
    case $ans in 
        add) op='+' ; break ;;
        subtract) op='-' ; break ;;
        multiply) op='*' ; break ;;
        divide) op='/' ; break ;;
        *) echo "invalid response" ;;
    esac
    done
    read -p "what's the second number? " n2
    ans=$(echo "$n1 $op $n2" | bc -l)
    printf "%s %s %s = %s\n\n" "$n1" "$op" "$n2" "$ans"
    
    exit 0
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-10-24
      • 1970-01-01
      • 2021-12-14
      • 1970-01-01
      • 2016-01-29
      • 1970-01-01
      • 2016-09-09
      • 1970-01-01
      相关资源
      最近更新 更多