我正在尝试在bash中实现连续除法算法 并且我面临一个问题,即循环中的模数之一返回错误结果
我尝试了多种主要计算((a%b)),expr和bc的模数的方法,但是都存在相同的问题
dec=$1
echo ----Dividing----
echo "dividing $dec by $2"
div=$((dec/$2))
echo "the result is $div"
rem=$((dec%$2))
res="$rem"
echo " the remainder is $rem"
while [ $div != 0 ]
do
div_old=$div
echo "dividing $div by $2"
div=$((div/$2))
echo "the result is $div"
rem=$(echo "$div % $2" | bc)
echo " the remainder is $rem"
if [ $rem != 0 ]
then
res="$rem$res"
else
res="$div_old$res"
fi
echo "for now the result is $res"
done
$ 1 = 2371和$ 2 = 5
预期结果为33441,但我的脚本返回33341
在此输出中看到
----Dividing----
dividing 2371 by 5
the result is 474
the remainder is 1
dividing 474 by 5
the result is 94
the remainder is 4
for now the result is 41
dividing 94 by 5
the result is 18
the remainder is 3
for now the result is 341
dividing 18 by 5
the result is 3
the remainder is 3
for now the result is 3341
dividing 3 by 5
the result is 0
the remainder is 0
for now the result is 33341
33341
但是当我尝试在脚本之外执行与
相同的操作时echo $(echo "94 % 5" | bc)
结果是4很好, 为什么循环的内部/外部之间会有这样的区别?
答案 0 :(得分:1)
div=$((div/$2))
...
rem=$(echo "$div % $2" | bc)
...
您要划分下一个div
,而不是旧的/当前的/前一个。您的意思是,划分旧的div,获取新的div,然后将相同的old_div与rem
一起使用:
div_old=$div
echo "dividing $div_old by $2"
div=$((div_old / $2))
echo "the result is $div"
rem=$((div_old % $2))
请注意,if [ $rem != 0 ]
正在进行字符串比较,它不等于数字。要将数字与[
或test
进行比较,请使用-ne
:
if [ $rem -ne 0 ]
或者仅使用bash算术扩展:
if ((rem != 0))
与while [ $div != 0 ]