基础二次公式计算器Shell脚本算术运算错误排查求助
Shell脚本算术运算错误排查与修复(二次方程求解脚本)
问题描述
我正在完成Unix课程的作业,这是我编写的第一份Shell脚本,计划用于期末提交。但脚本存在算术运算错误,无法排查解决,尤其在sqrt函数与bc工具的使用上遇到问题。已尝试调整语法但未奏效,附上脚本代码,恳请帮助:
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
错误分析与修复
你的脚本核心问题集中在bc工具调用、算术表达式语法、条件判断写法上,以下是逐个修复点:
颜色变量赋值错误
原代码中颜色变量的反引号赋值未闭合,导致后续逻辑混乱。建议用$()替代反引号(可读性更强),正确写法:lightgreen=$(echo -en "\e[92m") LIGHTRED=$(echo -en "\e[101m")bc工具调用逻辑错误$((...))是Shell内置算术扩展,不支持sqrt函数和管道到bc。必须通过命令替换$()调用bc,且需加-l参数启用数学库才能使用sqrt:- 错误写法:
sqrtd=$((sqrt($discrim) | bc )) - 正确写法:
sqrtd=$(echo "sqrt($discrim)" | bc -l)
- 错误写法:
二次方程根计算错误
根的计算必须通过bc完成,不能用$((...))包裹,同时要设置浮点运算精度:xone=$(echo "scale=4; (-$b + sqrt($discrim)) / (2 * $a)" | bc -l) xtwo=$(echo "scale=4; (-$b - sqrt($discrim)) / (2 * $a)" | bc -l)其中
scale=4用于设置小数点后保留4位,可按需调整。判别式条件判断错误
原判断缺少then,括号前后需加空格,且要处理判别式为负的情况(此时sqrt会报错):if [ $discrim -lt 0 ]; then echo "${LIGHTRED}There are no real solutions." exit 1 # 无实根时直接退出脚本 fi输出格式错误
原输出中颜色变量与内容间缺少空格,导致颜色失效,修正为:echo "${lightgreen}The discriminant is: $discrim"
完整修复后的脚本
#!/bin/bash # 定义颜色变量,添加重置色避免后续输出变色 lightgreen=$(echo -en "\e[92m") LIGHTRED=$(echo -en "\e[101m") reset=$(echo -en "\e[0m") echo "What are the values of a, b & c?" echo "a value:" read a echo "b value:" read b echo "c value:" read c # 计算判别式 discrim=$(($b**2 - 4*$a*$c)) echo "${lightgreen}The discriminant is: $discrim${reset}" # 判断是否存在实根 if [ $discrim -lt 0 ]; then echo "${LIGHTRED}There are no real solutions.${reset}" exit 1 fi # 计算平方根与方程根,保留4位小数 sqrtd=$(echo "sqrt($discrim)" | bc -l) xone=$(echo "scale=4; (-$b + $sqrtd) / (2 * $a)" | bc -l) xtwo=$(echo "scale=4; (-$b - $sqrtd) / (2 * $a)" | bc -l) echo "${lightgreen}The two solutions are: ${reset}$xone $xtwo"
关键说明
bc -l:启用数学库,提供sqrt等函数并支持浮点运算scale=N:设置bc运算精度,控制小数点后位数\e[0m:重置终端颜色,避免颜色影响后续输出- 脚本开头添加
#!/bin/bash:指定解释器,确保脚本正确执行
内容的提问来源于stack exchange,提问作者coltuwu
相关产品推荐
相关产品推荐

