linux shell中实现猜数字游戏

 

1、

复制代码
root@PC1:/home/test2# ls
test.sh
root@PC1:/home/test2# cat test.sh     ## 脚本
#!/bin/bash
ANSWER=$(expr $RANDOM % 100)
TIMES=0

echo "the range is 0-100, please guess."
while true
do
        read -p "please input your answer: " GUESS
        if [[ ! $GUESS =~ ^[0-9]+$ ]]
        then
                echo "please input an integer!"
                continue
        fi
        if [[ $GUESS -gt 100 || $GUESS -lt 0 ]]
        then
                echo "the range is 0-100! please try again!"
                continue
        fi
        let TIMES++
        if [ $GUESS -eq $ANSWER ]
        then
                echo "you are right!"
                echo "you have guess $TIMES time!"
                exit 0
        elif [ $GUESS -gt $ANSWER ]
        then
                echo "too big! please try again!"
        else
                echo "too small! please try again!"
        fi
done
复制代码

 

2、测试

复制代码
root@PC1:/home/test2# bash test.sh
the range is 0-100, please guess.
please input your answer: 60
too big! please try again!
please input your answer: abc
please input an integer!
please input your answer: 50
too big! please try again!
please input your answer: 400
the range is 0-100! please try again!
please input your answer: 30
too small! please try again!
please input your answer: 40
too big! please try again!
please input your answer: 35
too big! please try again!
please input your answer: 33
too small! please try again!
please input your answer: 34
you are right!
you have guess 7 time!
复制代码

 

posted @   小鲨鱼2018  阅读(295)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
历史上的今天:
2021-05-23 c语言中数字字符计数
2021-05-23 c语言中将输入的字符直接输出
2021-05-23 c语言8-9
点击右上角即可分享
微信分享提示