基本的二次公式计算器shell脚本问题



这是我为Unix类编写的第一个shell脚本,也是我希望提交给期末考试的脚本之一。然而,有几个扭结我似乎无法清除,它似乎是算术运算错误,我似乎无法计算出来。请善良一点!非常感谢您的宝贵时间。

lightgreen=`echo -en "e[92m"
echo What are the values of a, b & c?
LIGHTRED=`echo -en "e[101m"
echo a value:
read a

echo b value:
read b
echo c value:
read c
discrim=$(($b**2 - 4*$a*$c))
sqrtd=$((sqrt($discrim) | bc ))
echo test $sqrtd

echo ${lightgreen}The discriminant is:${discrim}
#xone=$((( -$b + sqrt$discrim) / (2 * $a) | bc ))
#xtwo=$((( -$b - sqrt$discrim) / (2 * $a) | bc ))
xone=$((echo (-1*$b + sqrt($discrim)) / (2*$a) | bc ))
xtwo=$((echo (-1*$b - sqrt($discrim)) / (2*$a) | bc ))
echo ${lightgreen}The discriminant is:${discrim}
#if [$discrim -lt 0 ]
#       echo $LIGHTRED There are no real solutions.
#
#
#
echo The two solutions are $xone $xtwo

我试过把语法弄得一团糟,我不确定是括号把我搞砸了还是sqrt函数,我试过合并| bc但无济于事。任何帮助都非常感谢!:)

不要犹豫,拨打man bash,man bc手册页

使用https://www.shellcheck.net/检查shell脚本。Shellcheck也存在于命令行和Visual Studio Code中,扩展名为。

#! /usr/bin/env bash
# The first line is very important to now the name of the interpreter
# Always close " , ' , or ` sequences with same character
# Do not use old `...` syntax, replaced by $(...)
# Here, use $'...', to assign value with ... sequences
lightgreen=$'e[92m'
lightred=$'e[101m'
normal=$'e[0m'
# It's better to put phrase between "..." or '...'
echo "What are the values of a, b & c?"

# Use read -p option to specify prompt
# Use read -r option to not act backslash as an escape character
read -p "a value: " -r a
read -p "b value: " -r b
read -p "c value: " -r c
# With bash only, it's only possible to use integer values
# discrim=$(($b**2 - 4*$a*$c))
# use bc instead
discrim=$(bc -l <<<"$b^2 - 4*$a*$c")
# The syntax:
#    bc <<<"..."
# is equivalent to:
#    echo "..." | bc
# but without pipe (|)
# Close the color change with normal return
echo "${lightgreen}The discriminant is: ${discrim}${normal}"
if [[ "${discrim:0:1}" == "-" ]]; then
echo "${lightred}There are no real solutions${normal}"
# ... complex ...
else
sqrtd=$(bc -l <<<"sqrt($discrim)")
echo "sqrt($discrim)=$sqrtd"
xone=$(bc -l <<<"(-1*$b + $sqrtd) / (2*$a)")
xtwo=$(bc -l <<<"(-1*$b - $sqrtd) / (2*$a)")
echo "The two solutions are: $xone and $xtwo"
fi

最新更新