我的UNIX猜数游戏存在逻辑问题。菜单系统工作正常(1个用于游戏,2个用于退出,否则防御性响应)。但是在游戏中我得到的输出如下:
这是代码(FYI,这是在KSH shell中)。我猜我在某处有某种语法错误......
#!/bin/ksh
# CS2351 - UNIX Programming
# Program 1
x=$RANDOM%100+1
tries=0
guessInt=0
userOption=0
while ((1==1))
do
print "Welcome to the UNIX Number Guessing Game!"
print "A random number between 1 and 20 has been selected."
print "===========\nDirections: \n==========="
print "1. Enter your guess. The program will tell you if it is high or low."
print "2. The program will tell you if it is high or low."
print "3. Change your guess."
print "4. The computer will tell you how many guesses you had."
print "=======\nOPTIONS\n======="
print "1: Play \n2: Exit"
print "Enter number 1 or 2."
"Enter number 1 or 2."
read userinput
case "$userinput" in
1)
break;;
2)
print "Quitting program!!!"
exit;;
*)
print "The input $userinput is invalid."
print "Returning to main menu..."
print "\n\n\n";;
esac
done
print "Please enter you're guess."
read guessInt
while (($guessInt != "q"));
do
if [$guessInt -lt $x];
then
print "Your guess is too low, try again! (q to quit)."
tries=tries+1
elif [$guessInt -gt $x];
then
print "Your guess is too high, try again! (q to quit)."
tries=tries+1
else
print "Yay!!! $guessInt is the right number!!!"
break
fi
done
print "Your total number of tries were $tries."
exit
对此问题的任何见解表示赞赏!
答案 0 :(得分:1)
据我所知,你需要双括号作为条件,一些空格很重要。你需要这样的东西:
if [[ $guessInt -lt $x ]]; then
tries
也应该从1开始,因为如果不先猜测你就无法获胜。
如果他们的猜测是错误的,你还应该在while循环中再次阅读guessInt
,因为如果你第一次猜错了,它将永远重复(因为$guessInt
的值不是在循环的迭代之间改变。)
看看these shell script syntax examples;它有很多bash的东西,但也有一些不错的ksh覆盖率。