linux 中while循环实现猜数字游戏

 

1、

[root@rhel7pc1 test]# cat test.sh
#!/bin/bash
NUM=$[RANDOM % 100 + 1]
TIMES=0
while :
  do
        read -p "please input a 1~100 num: " ANS
        TIMES=$[TIMES+1]
        if [ $ANS -eq $NUM ]
        then
                echo "yes, your answer is right!"
                echo "you had guessed $TIMES times!!"
                exit
        elif [ $ANS -gt $NUM ]
        then
                echo "too big!"
        else
                echo "too small!"
        fi
done
[root@rhel7pc1 test]# ls
test.sh
[root@rhel7pc1 test]# bash test.sh
please input a 1~100 num: 50
too small!
please input a 1~100 num: 80
too big!
please input a 1~100 num: 60
too small!
please input a 1~100 num: 70
too big!
please input a 1~100 num: 65
too small!
please input a 1~100 num: 67
too big!
please input a 1~100 num: 66
yes, your answer is right!
you had guessed 7 times!!

 

posted @ 2022-04-16 13:58  小鲨鱼2018  阅读(214)  评论(0编辑  收藏  举报