需求:共有5家商店,逐个逛,买商品则打印商品信息,记录每次购买的金额。逛完5家商店给予总金额输出
分析:大循环逛5家商店,小循环询问是否购买商品,每次买完,对商品价格累加。#!/bin/bash
#打印商品价格函数
info() {
printf " Price list
1、hat 50¥
2、shoes 200¥
3、clothes 300¥
4、trousers 100¥
5、glove 30¥
"
}
#小循环选择商品,并累加价格。
shopping() {
if [ $act == "y" ];then
read -p "Please choose the goods.(1-5): " buy
case $buy in
1)
#这里用的数组索引++,最终用索引对应值*价格
#等同于 let hatsum=$[hatsum+50]
let hat[1]++
hatsum=$[${hat[1]} * 50 ]
echo "You spent ${hatsum}¥ on the hat"
;;
2)
let shoes[2]++
shoessum=$[${shoes[2]} * 200 ]
echo "You spent ${shoessum}¥ on the shoes"
;;
3)
let clothes[3]++
clothessum=$[${clothes[3]} * 300 ]
echo "You spent ${clothessum}¥ on the clothes"
;;
4)
let tro[4]++
trosum=$[${tro[4]} * 100 ]
echo "You spent ${trosum}¥ on the trosum"
;;
5)
let glove[5]++
glovesum=$[${glove[5]} * 30 ]
echo "You spent ${glovesum}¥ on the glove"
;;
*)
echo "please enter number 1-5......"
;;
esac
else
break
fi
}
#大循环逛5家商店,如果为y则执行小循环,n,或者其他则continue,跳过本次循环。这里判断不严谨,不为n也会跳过本次循环。
for i in `seq 5`
do
read -p "Pass the $i store,Go in and have a look?(y/n): " cho
if [ "$cho" = "y" ];then
while :
do
info
read -p "Do you want to buy anything?(y/n): " act
shopping
done
else
continue
fi
done