分类:
2010-09-09 23:55:35
有个猴子手里有22元,去买汽水喝,一瓶汽水是1元,三个空瓶可以换取一瓶汽水,问该猴子可以喝多少水?
使用shell脚本方式实现
vi monkey.sh
#!/bin/bash
read -p 'input the number of money: ' count //钱数
read -p 'inout the average of fruit: ' bs //单价
read -p 'input the change of fruit: ' chg //交换价
#count=22
#bs=1
#chg=3 //测试使用
A=$(($count/$chg)) //空瓶可换汽水数
B=$(($count%$chg)) //换后的空瓶数
tmp[1]=$A
sum=0
b=$B
for i in $(seq 1 5 )
do
tmp[$(($i+1))]=$(($((${tmp[$i]}+$b))/$chg)) //计算所有空瓶可换汽水数
echo -n "tmp:" ${tmp[$(($i+1))]} " "
b=$(($((${tmp[$i]}+$b))%$chg)) //显示中间产生空瓶数值
echo "b:"$b
sum=$(( $sum+${tmp[$(($i+1))]} )) //计算此次可喝汽水数
done
[ $b -eq 2 ]&&sum=$(($sum+1))||sum=$sum //如果有2个空瓶时,可借
//一空瓶后喝完再还回去
echo $(($count+$A+$sum))
上面的是原型,下面给大家通用型的:
#!/bin/bash
read -p 'input the number of money: ' count
read -p 'inout the average of fruit: ' bs
read -p 'input the change of fruit: ' chg
A=$(($((count/bs))/$chg))
B=$(($((count/bs))%$chg))
tmp[1]=$A
sum=0
b=$B
for i in $(seq 1 9 )
do
tmp[$(($i+1))]=$(($((${tmp[$i]}+$b))/$chg))
echo -en "tmp:" ${tmp[$(($i+1))]} " "
b=$(($((${tmp[$i]}+$b))%$chg))
echo "b:"$b
sum=$(( $sum+${tmp[$(($i+1))]} ))
done
[ $b -eq $((chg-1)) ]&&sum=$(($sum+1))
echo $((count/bs))"+"$A"+"$sum"="$(($((count/bs))+$A+$sum))